vendor: 4,539 bytes, lines 1-163
1/** 2 * @license AngularJS v1.6.6 3 * (c) 2010-2017 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}; 17 18/** 19 * @ngdoc function 20 * @name angular.errorHandlingConfig 21 * @module ng 22 * @kind function 23 * 24 * @description 25 * Configure several aspects of error handling in AngularJS if used as a setter or return the 26 * current configuration if used as a getter. The following options are supported: 27 * 28 * - **objectMaxDepth**: The maximum depth to which objects are traversed when stringified for error messages. 29 * 30 * Omitted or undefined options will leave the corresponding configuration values unchanged. 31 * 32 * @param {Object=} config - The configuration object. May only contain the options that need to be 33 * updated. Supported keys: 34 * 35 * * `objectMaxDepth` **{Number}** - The max depth for stringifying objects. Setting to a 36 * non-positive or non-numeric value, removes the max depth limit. 37 * Default: 5 38 */ 39function errorHandlingConfig(config) { 40 if (isObject(config)) { 41 if (isDefined(config.objectMaxDepth)) { 42 minErrConfig.objectMaxDepth = isValidObjectMaxDepth(config.objectMaxDepth) ? config.objectMaxDepth : NaN; 43 } 44 } else { 45 return minErrConfig; 46 } 47} 48 49/** 50 * @private 51 * @param {Number} maxDepth 52 * @return {boolean} 53 */ 54function isValidObjectMaxDepth(maxDepth) { 55 return isNumber(maxDepth) && maxDepth > 0; 56} 57 58/** 59 * @description 60 * 61 * This object provides a utility for producing rich Error messages within 62 * Angular. It can be called as follows: 63 * 64 * var exampleMinErr = minErr('example'); 65 * throw exampleMinErr('one', 'This {0} is {1}', foo, bar); 66 * 67 * The above creates an instance of minErr in the example namespace. The 68 * resulting error will have a namespaced error code of example.one. The 69 * resulting error will replace {0} with the value of foo, and {1} with the 70 * value of bar. The object is not restricted in the number of arguments it can 71 * take. 72 * 73 * If fewer arguments are specified than necessary for interpolation, the extra 74 * interpolation markers will be preserved in the final string. 75 * 76 * Since data will be parsed statically during a build step, some restrictions 77 * are applied with respect to how minErr instances are created and called. 78 * Instances should have names of the form namespaceMinErr for a minErr created 79 * using minErr('namespace') . Error codes, namespaces and template strings 80 * should all be static strings, not variables or general expressions. 81 * 82 * @param {string} module The namespace to use for the new minErr instance. 83 * @param {function} ErrorConstructor Custom error constructor to be instantiated when returning 84 * error from returned function, for cases when a particular type of error is useful. 85 * @returns {function(code:string, template:string, ...templateArgs): Error} minErr instance 86 */ 87 88function minErr(module, ErrorConstructor) { 89 ErrorConstructor = ErrorConstructor || Error; 90 return function() { 91 var code = arguments[0], 92 template = arguments[1], 93 message = '[' + (module ? module + ':' : '') + code + '] ', 94 templateArgs = sliceArgs(arguments, 2).map(function(arg) { 95 return toDebugString(arg, minErrConfig.objectMaxDepth); 96 }), 97 paramPrefix, i; 98 99 message += template.replace(/\{\d+\}/g, function(match) { 100 var index = +match.slice(1, -1); 101 102 if (index < templateArgs.length) { 103 return templateArgs[index]; 104 } 105 106 return match; 107 }); 108 109 message += '\nhttp://errors.angularjs.org/1.6.6/' + 110 (module ? module + '/' : '') + code; 111 112 for (i = 0, paramPrefix = '?'; i < templateArgs.length; i++, paramPrefix = '&') { 113 message += paramPrefix + 'p' + i + '=' + encodeURIComponent(templateArgs[i]); 114 } 115 116 return new ErrorConstructor(message); 117 }; 118} 119 120/* We need to tell ESLint what variables are being exported */ 121/* exported 122 angular, 123 msie, 124 jqLite, 125 jQuery, 126 slice, 127 splice, 128 push, 129 toString, 130 minErrConfig, 131 errorHandlingConfig, 132 isValidObjectMaxDepth, 133 ngMinErr, 134 angularModule, 135 uid, 136 REGEX_STRING_REGEXP, 137 VALIDITY_STATE_PROPERTY, 138 139 lowercase, 140 uppercase, 141 manualLowercase, 142 manualUppercase, 143 nodeName_, 144 isArrayLike, 145 forEach, 146 forEachSorted, 147 reverseParams, 148 nextUid, 149 setHashKey, 150 extend, 151 toInt, 152 inherit, 153 merge, 154 noop, 155 identity, 156 valueFn, 157 isUndefined, 158 isDefined, 159 isObject, 160 isBlankObject, 161 isString, 162 isNumber, 163 isNumberNaN,
164 isDate, 165 isError, 166 isArray, 167 isFunction, 168 isRegExp, 169 isWindow, 170 isScope, 171 isFile, 172 isFormData, 173 isBlob, 174 isBoolean, 175 isPromiseLike, 176 trim, 177 escapeForRegexp, 178 isElement, 179 makeMap, 180 includes, 181 arrayRemove, 182 copy, 183 simpleCompare, 184 equals, 185 csp, 186 jq, 187 concat, 188 sliceArgs, 189 bind, 190 toJsonReplacer, 191 toJson, 192 fromJson, 193 convertTimezoneToLocal, 194 timezoneToOffset, 195 startingTag, 196 tryDecodeURIComponent, 197 parseKeyValue, 198 toKeyValue, 199 encodeUriSegment, 200 encodeUriQuery, 201 angularInit, 202 bootstrap, 203 getTestability, 204 snake_case, 205 bindJQuery, 206 assertArg, 207 assertArgFn, 208 assertNotHasOwnProperty, 209 getter, 210 getBlockNodes, 211 hasOwnProperty, 212 createMap, 213 stringify, 214 215 NODE_TYPE_ELEMENT, 216 NODE_TYPE_ATTRIBUTE, 217 NODE_TYPE_TEXT, 218 NODE_TYPE_COMMENT, 219 NODE_TYPE_DOCUMENT, 220 NODE_TYPE_DOCUMENT_FRAGMENT 221*/ 222 223//////////////////////////////////// 224 225/** 226 * @ngdoc module 227 * @name ng 228 * @module ng 229 * @installation 230 * @description 231 * 232 * # ng (core module) 233 * The ng module is loaded by default when an AngularJS application is started. The module itself 234 * contains the essential components for an AngularJS application to function. The table below 235 * lists a high level breakdown of each of the services/factories, filters, directives and testing 236 * components available within this core module. 237 * 238 * <div doc-module-components="ng"></div> 239 */ 240 241var REGEX_STRING_REGEXP = /^\/(.+)\/([a-z]*)$/; 242 243// The name of a form control's ValidityState property. 244// This is used so that it's possible for internal tests to create mock ValidityStates. 245var VALIDITY_STATE_PROPERTY = 'validity'; 246 247 248var hasOwnProperty = Object.prototype.hasOwnProperty; 249 250/** 251 * @ngdoc function 252 * @name angular.lowercase 253 * @module ng 254 * @kind function 255 * 256 * @deprecated 257 * sinceVersion="1.5.0" 258 * removeVersion="1.7.0" 259 * Use [String.prototype.toLowerCase](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String/toLowerCase) instead. 260 * 261 * @description Converts the specified string to lowercase. 262 * @param {string} string String to be converted to lowercase. 263 * @returns {string} Lowercased string. 264 */ 265var lowercase = function(string) {return isString(string) ? string.toLowerCase() : string;}; 266 267/** 268 * @ngdoc function 269 * @name angular.uppercase 270 * @module ng 271 * @kind function 272 * 273 * @deprecated 274 * sinceVersion="1.5.0" 275 * removeVersion="1.7.0" 276 * Use [String.prototype.toUpperCase](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String/toUpperCase) instead. 277 * 278 * @description Converts the specified string to uppercase. 279 * @param {string} string String to be converted to uppercase. 280 * @returns {string} Uppercased string. 281 */ 282var uppercase = function(string) {return isString(string) ? string.toUpperCase() : string;}; 283 284 285var manualLowercase = function(s) { 286 /* eslint-disable no-bitwise */ 287 return isString(s) 288 ? s.replace(/[A-Z]/g, function(ch) {return String.fromCharCode(ch.charCodeAt(0) | 32);}) 289 : s; 290 /* eslint-enable */ 291}; 292var manualUppercase = function(s) { 293 /* eslint-disable no-bitwise */ 294 return isString(s) 295 ? s.replace(/[a-z]/g, function(ch) {return String.fromCharCode(ch.charCodeAt(0) & ~32);}) 296 : s; 297 /* eslint-enable */ 298}; 299 300 301// String#toLowerCase and String#toUpperCase don't produce correct results in browsers with Turkish 302// locale, for this reason we need to detect this case and redefine lowercase/uppercase methods 303// with correct but slower alternatives. See https://github.com/angular/angular.js/issues/11387 304if ('i' !== 'I'.toLowerCase()) { 305 lowercase = manualLowercase; 306 uppercase = manualUppercase; 307} 308 309 310var 311 msie, // holds major version number for IE, or NaN if UA is not IE. 312 jqLite, // delay binding since jQuery could be loaded after us. 313 jQuery, // delay binding 314 slice = [].slice, 315 splice = [].splice, 316 push = [].push, 317 toString = Object.prototype.toString, 318 getPrototypeOf = Object.getPrototypeOf, 319 ngMinErr = minErr('ng'), 320 321 /** @name angular */ 322 angular = window.angular || (window.angular = {}), 323 angularModule, 324 uid = 0; 325 326// Support: IE 9-11 only 327/** 328 * documentMode is an IE-only property
vendor: 17,584 bytes, lines 329-968
329 * http://msdn.microsoft.com/en-us/library/ie/cc196988(v=vs.85).aspx 330 */ 331msie = window.document.documentMode; 332 333 334/** 335 * @private 336 * @param {*} obj 337 * @return {boolean} Returns true if `obj` is an array or array-like object (NodeList, Arguments, 338 * String ...) 339 */ 340function isArrayLike(obj) { 341 342 // `null`, `undefined` and `window` are not array-like 343 if (obj == null || isWindow(obj)) return false; 344 345 // arrays, strings and jQuery/jqLite objects are array like 346 // * jqLite is either the jQuery or jqLite constructor function 347 // * we have to check the existence of jqLite first as this method is called 348 // via the forEach method when constructing the jqLite object in the first place 349 if (isArray(obj) || isString(obj) || (jqLite && obj instanceof jqLite)) return true; 350 351 // Support: iOS 8.2 (not reproducible in simulator) 352 // "length" in obj used to prevent JIT error (gh-11508) 353 var length = 'length' in Object(obj) && obj.length; 354 355 // NodeList objects (with `item` method) and 356 // other objects with suitable length characteristics are array-like 357 return isNumber(length) && 358 (length >= 0 && ((length - 1) in obj || obj instanceof Array) || typeof obj.item === 'function'); 359 360} 361 362/** 363 * @ngdoc function 364 * @name angular.forEach 365 * @module ng 366 * @kind function 367 * 368 * @description 369 * Invokes the `iterator` function once for each item in `obj` collection, which can be either an 370 * object or an array. The `iterator` function is invoked with `iterator(value, key, obj)`, where `value` 371 * is the value of an object property or an array element, `key` is the object property key or 372 * array element index and obj is the `obj` itself. Specifying a `context` for the function is optional. 373 * 374 * It is worth noting that `.forEach` does not iterate over inherited properties because it filters 375 * using the `hasOwnProperty` method. 376 * 377 * Unlike ES262's 378 * [Array.prototype.forEach](http://www.ecma-international.org/ecma-262/5.1/#sec-15.4.4.18), 379 * providing 'undefined' or 'null' values for `obj` will not throw a TypeError, but rather just 380 * return the value provided. 381 * 382 ```js 383 var values = {name: 'misko', gender: 'male'}; 384 var log = []; 385 angular.forEach(values, function(value, key) { 386 this.push(key + ': ' + value); 387 }, log); 388 expect(log).toEqual(['name: misko', 'gender: male']); 389 ``` 390 * 391 * @param {Object|Array} obj Object to iterate over. 392 * @param {Function} iterator Iterator function. 393 * @param {Object=} context Object to become context (`this`) for the iterator function. 394 * @returns {Object|Array} Reference to `obj`. 395 */ 396 397function forEach(obj, iterator, context) { 398 var key, length; 399 if (obj) { 400 if (isFunction(obj)) { 401 for (key in obj) { 402 if (key !== 'prototype' && key !== 'length' && key !== 'name' && obj.hasOwnProperty(key)) { 403 iterator.call(context, obj[key], key, obj); 404 } 405 } 406 } else if (isArray(obj) || isArrayLike(obj)) { 407 var isPrimitive = typeof obj !== 'object'; 408 for (key = 0, length = obj.length; key < length; key++) { 409 if (isPrimitive || key in obj) { 410 iterator.call(context, obj[key], key, obj); 411 } 412 } 413 } else if (obj.forEach && obj.forEach !== forEach) { 414 obj.forEach(iterator, context, obj); 415 } else if (isBlankObject(obj)) { 416 // createMap() fast path --- Safe to avoid hasOwnProperty check because prototype chain is empty 417 for (key in obj) { 418 iterator.call(context, obj[key], key, obj); 419 } 420 } else if (typeof obj.hasOwnProperty === 'function') { 421 // Slow path for objects inheriting Object.prototype, hasOwnProperty check needed 422 for (key in obj) { 423 if (obj.hasOwnProperty(key)) { 424 iterator.call(context, obj[key], key, obj); 425 } 426 } 427 } else { 428 // Slow path for objects which do not have a method `hasOwnProperty` 429 for (key in obj) { 430 if (hasOwnProperty.call(obj, key)) { 431 iterator.call(context, obj[key], key, obj); 432 } 433 } 434 } 435 } 436 return obj; 437} 438 439function forEachSorted(obj, iterator, context) { 440 var keys = Object.keys(obj).sort(); 441 for (var i = 0; i < keys.length; i++) { 442 iterator.call(context, obj[keys[i]], keys[i]); 443 } 444 return keys; 445} 446 447 448/** 449 * when using forEach the params are value, key, but it is often useful to have key, value. 450 * @param {function(string, *)} iteratorFn 451 * @returns {function(*, string)} 452 */ 453function reverseParams(iteratorFn) { 454 return function(value, key) {iteratorFn(key, value);}; 455} 456 457/** 458 * A consistent way of creating unique IDs in angular. 459 * 460 * Using simple numbers allows us to generate 28.6 million unique ids per second for 10 years before 461 * we hit number precision issues in JavaScript. 462 * 463 * Math.pow(2,53) / 60 / 60 / 24 / 365 / 10 = 28.6M 464 * 465 * @returns {number} an unique alpha-numeric string 466 */ 467function nextUid() { 468 return ++uid; 469} 470 471 472/** 473 * Set or clear the hashkey for an object. 474 * @param obj object 475 * @param h the hashkey (!truthy to delete the hashkey) 476 */ 477function setHashKey(obj, h) { 478 if (h) { 479 obj.$$hashKey = h; 480 } else { 481 delete obj.$$hashKey; 482 } 483} 484 485 486function baseExtend(dst, objs, deep) { 487 var h = dst.$$hashKey; 488 489 for (var i = 0, ii = objs.length; i < ii; ++i) { 490 var obj = objs[i]; 491 if (!isObject(obj) && !isFunction(obj)) continue; 492 var keys = Object.keys(obj); 493 for (var j = 0, jj = keys.length; j < jj; j++) { 494 var key = keys[j]; 495 var src = obj[key]; 496 497 if (deep && isObject(src)) { 498 if (isDate(src)) { 499 dst[key] = new Date(src.valueOf()); 500 } else if (isRegExp(src)) { 501 dst[key] = new RegExp(src); 502 } else if (src.nodeName) { 503 dst[key] = src.cloneNode(true); 504 } else if (isElement(src)) { 505 dst[key] = src.clone(); 506 } else { 507 if (!isObject(dst[key])) dst[key] = isArray(src) ? [] : {}; 508 baseExtend(dst[key], [src], true); 509 } 510 } else { 511 dst[key] = src; 512 } 513 } 514 } 515 516 setHashKey(dst, h); 517 return dst; 518} 519 520/** 521 * @ngdoc function 522 * @name angular.extend 523 * @module ng 524 * @kind function 525 * 526 * @description 527 * 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.extend({}, object1, object2)`. 530 * 531 * **Note:** Keep in mind that `angular.extend` does not support recursive merge (deep copy). Use 532 * {@link angular.merge} for this. 533 * 534 * @param {Object} dst Destination object. 535 * @param {...Object} src Source object(s). 536 * @returns {Object} Reference to `dst`. 537 */ 538function extend(dst) { 539 return baseExtend(dst, slice.call(arguments, 1), false); 540} 541 542 543/** 544* @ngdoc function 545* @name angular.merge 546* @module ng 547* @kind function 548* 549* @description 550* Deeply extends the destination object `dst` by copying own enumerable properties from the `src` object(s) 551* to `dst`. You can specify multiple `src` objects. If you want to preserve original objects, you can do so 552* by passing an empty object as the target: `var object = angular.merge({}, object1, object2)`. 553* 554* Unlike {@link angular.extend extend()}, `merge()` recursively descends into object properties of source 555* objects, performing a deep copy. 556* 557* @deprecated 558* sinceVersion="1.6.5" 559* This function is deprecated, but will not be removed in the 1.x lifecycle. 560* There are edge cases (see {@link angular.merge#known-issues known issues}) that are not 561* supported by this function. We suggest 562* using [lodash's merge()](https://lodash.com/docs/4.17.4#merge) instead. 563* 564* @knownIssue 565* This is a list of (known) object types that are not handled correctly by this function: 566* - [`Blob`](https://developer.mozilla.org/docs/Web/API/Blob) 567* - [`MediaStream`](https://developer.mozilla.org/docs/Web/API/MediaStream) 568* - [`CanvasGradient`](https://developer.mozilla.org/docs/Web/API/CanvasGradient) 569* - AngularJS {@link $rootScope.Scope scopes}; 570* 571* @param {Object} dst Destination object. 572* @param {...Object} src Source object(s). 573* @returns {Object} Reference to `dst`. 574*/ 575function merge(dst) { 576 return baseExtend(dst, slice.call(arguments, 1), true); 577} 578 579 580 581function toInt(str) { 582 return parseInt(str, 10); 583} 584 585var isNumberNaN = Number.isNaN || function isNumberNaN(num) { 586 // eslint-disable-next-line no-self-compare 587 return num !== num; 588}; 589 590 591function inherit(parent, extra) { 592 return extend(Object.create(parent), extra); 593} 594 595/** 596 * @ngdoc function 597 * @name angular.noop 598 * @module ng 599 * @kind function 600 * 601 * @description 602 * A function that performs no operations. This function can be useful when writing code in the 603 * functional style. 604 ```js 605 function foo(callback) { 606 var result = calculateResult(); 607 (callback || angular.noop)(result); 608 } 609 ``` 610 */ 611function noop() {} 612noop.$inject = []; 613 614 615/** 616 * @ngdoc function 617 * @name angular.identity 618 * @module ng 619 * @kind function 620 * 621 * @description 622 * A function that returns its first argument. This function is useful when writing code in the 623 * functional style. 624 * 625 ```js 626 function transformer(transformationFn, value) { 627 return (transformationFn || angular.identity)(value); 628 }; 629 630 // E.g. 631 function getResult(fn, input) { 632 return (fn || angular.identity)(input); 633 }; 634 635 getResult(function(n) { return n * 2; }, 21); // returns 42 636 getResult(null, 21); // returns 21 637 getResult(undefined, 21); // returns 21 638 ``` 639 * 640 * @param {*} value to be returned. 641 * @returns {*} the value passed in. 642 */ 643function identity($) {return $;} 644identity.$inject = []; 645 646 647function valueFn(value) {return function valueRef() {return value;};} 648 649function hasCustomToString(obj) { 650 return isFunction(obj.toString) && obj.toString !== toString; 651} 652 653 654/** 655 * @ngdoc function 656 * @name angular.isUndefined 657 * @module ng 658 * @kind function 659 * 660 * @description 661 * Determines if a reference is undefined. 662 * 663 * @param {*} value Reference to check. 664 * @returns {boolean} True if `value` is undefined. 665 */ 666function isUndefined(value) {return typeof value === 'undefined';} 667 668 669/** 670 * @ngdoc function 671 * @name angular.isDefined 672 * @module ng 673 * @kind function 674 * 675 * @description 676 * Determines if a reference is defined. 677 * 678 * @param {*} value Reference to check. 679 * @returns {boolean} True if `value` is defined. 680 */ 681function isDefined(value) {return typeof value !== 'undefined';} 682 683 684/** 685 * @ngdoc function 686 * @name angular.isObject 687 * @module ng 688 * @kind function 689 * 690 * @description 691 * Determines if a reference is an `Object`. Unlike `typeof` in JavaScript, `null`s are not 692 * considered to be objects. Note that JavaScript arrays are objects. 693 * 694 * @param {*} value Reference to check. 695 * @returns {boolean} True if `value` is an `Object` but not `null`. 696 */ 697function isObject(value) { 698 // http://jsperf.com/isobject4 699 return value !== null && typeof value === 'object'; 700} 701 702 703/** 704 * Determine if a value is an object with a null prototype 705 * 706 * @returns {boolean} True if `value` is an `Object` with a null prototype 707 */ 708function isBlankObject(value) { 709 return value !== null && typeof value === 'object' && !getPrototypeOf(value); 710} 711 712 713/** 714 * @ngdoc function 715 * @name angular.isString 716 * @module ng 717 * @kind function 718 * 719 * @description 720 * Determines if a reference is a `String`. 721 * 722 * @param {*} value Reference to check. 723 * @returns {boolean} True if `value` is a `String`. 724 */ 725function isString(value) {return typeof value === 'string';} 726 727 728/** 729 * @ngdoc function 730 * @name angular.isNumber 731 * @module ng 732 * @kind function 733 * 734 * @description 735 * Determines if a reference is a `Number`. 736 * 737 * This includes the "special" numbers `NaN`, `+Infinity` and `-Infinity`. 738 * 739 * If you wish to exclude these then you can use the native 740 * [`isFinite'](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/isFinite) 741 * method. 742 * 743 * @param {*} value Reference to check. 744 * @returns {boolean} True if `value` is a `Number`. 745 */ 746function isNumber(value) {return typeof value === 'number';} 747 748 749/** 750 * @ngdoc function 751 * @name angular.isDate 752 * @module ng 753 * @kind function 754 * 755 * @description 756 * Determines if a value is a date. 757 * 758 * @param {*} value Reference to check. 759 * @returns {boolean} True if `value` is a `Date`. 760 */ 761function isDate(value) { 762 return toString.call(value) === '[object Date]'; 763} 764 765 766/** 767 * @ngdoc function 768 * @name angular.isArray 769 * @module ng 770 * @kind function 771 * 772 * @description 773 * Determines if a reference is an `Array`. Alias of Array.isArray. 774 * 775 * @param {*} value Reference to check. 776 * @returns {boolean} True if `value` is an `Array`. 777 */ 778var isArray = Array.isArray; 779 780/** 781 * @description 782 * Determines if a reference is an `Error`. 783 * Loosely based on https://www.npmjs.com/package/iserror 784 * 785 * @param {*} value Reference to check. 786 * @returns {boolean} True if `value` is an `Error`. 787 */ 788function isError(value) { 789 var tag = toString.call(value); 790 switch (tag) { 791 case '[object Error]': return true; 792 case '[object Exception]': return true; 793 case '[object DOMException]': return true; 794 default: return value instanceof Error; 795 } 796} 797 798/** 799 * @ngdoc function 800 * @name angular.isFunction 801 * @module ng 802 * @kind function 803 * 804 * @description 805 * Determines if a reference is a `Function`. 806 * 807 * @param {*} value Reference to check. 808 * @returns {boolean} True if `value` is a `Function`. 809 */ 810function isFunction(value) {return typeof value === 'function';} 811 812 813/** 814 * Determines if a value is a regular expression object. 815 * 816 * @private 817 * @param {*} value Reference to check. 818 * @returns {boolean} True if `value` is a `RegExp`. 819 */ 820function isRegExp(value) { 821 return toString.call(value) === '[object RegExp]'; 822} 823 824 825/** 826 * Checks if `obj` is a window object. 827 * 828 * @private 829 * @param {*} obj Object to check 830 * @returns {boolean} True if `obj` is a window obj. 831 */ 832function isWindow(obj) { 833 return obj && obj.window === obj; 834} 835 836 837function isScope(obj) { 838 return obj && obj.$evalAsync && obj.$watch; 839} 840 841 842function isFile(obj) { 843 return toString.call(obj) === '[object File]'; 844} 845 846 847function isFormData(obj) { 848 return toString.call(obj) === '[object FormData]'; 849} 850 851 852function isBlob(obj) { 853 return toString.call(obj) === '[object Blob]'; 854} 855 856 857function isBoolean(value) { 858 return typeof value === 'boolean'; 859} 860 861 862function isPromiseLike(obj) { 863 return obj && isFunction(obj.then); 864} 865 866 867var TYPED_ARRAY_REGEXP = /^\[object (?:Uint8|Uint8Clamped|Uint16|Uint32|Int8|Int16|Int32|Float32|Float64)Array]$/; 868function isTypedArray(value) { 869 return value && isNumber(value.length) && TYPED_ARRAY_REGEXP.test(toString.call(value)); 870} 871 872function isArrayBuffer(obj) { 873 return toString.call(obj) === '[object ArrayBuffer]'; 874} 875 876 877var trim = function(value) { 878 return isString(value) ? value.trim() : value; 879}; 880 881// Copied from: 882// http://docs.closure-library.googlecode.com/git/local_closure_goog_string_string.js.source.html#line1021 883// Prereq: s is a string. 884var escapeForRegexp = function(s) { 885 return s 886 .replace(/([-()[\]{}+?*.$^|,:#<!\\])/g, '\\$1') 887 // eslint-disable-next-line no-control-regex 888 .replace(/\x08/g, '\\x08'); 889}; 890 891 892/** 893 * @ngdoc function 894 * @name angular.isElement 895 * @module ng 896 * @kind function 897 * 898 * @description 899 * Determines if a reference is a DOM element (or wrapped jQuery element). 900 * 901 * @param {*} value Reference to check. 902 * @returns {boolean} True if `value` is a DOM element (or wrapped jQuery element). 903 */ 904function isElement(node) { 905 return !!(node && 906 (node.nodeName // We are a direct element. 907 || (node.prop && node.attr && node.find))); // We have an on and find method part of jQuery API. 908} 909 910/** 911 * @param str 'key1,key2,...' 912 * @returns {object} in the form of {key1:true, key2:true, ...} 913 */ 914function makeMap(str) { 915 var obj = {}, items = str.split(','), i; 916 for (i = 0; i < items.length; i++) { 917 obj[items[i]] = true; 918 } 919 return obj; 920} 921 922 923function nodeName_(element) { 924 return lowercase(element.nodeName || (element[0] && element[0].nodeName)); 925} 926 927function includes(array, obj) { 928 return Array.prototype.indexOf.call(array, obj) !== -1; 929} 930 931function arrayRemove(array, value) { 932 var index = array.indexOf(value); 933 if (index >= 0) { 934 array.splice(index, 1); 935 } 936 return index; 937} 938 939/** 940 * @ngdoc function 941 * @name angular.copy 942 * @module ng 943 * @kind function 944 * 945 * @description 946 * Creates a deep copy of `source`, which should be an object or an array. 947 * 948 * * If no destination is supplied, a copy of the object or array is created. 949 * * If a destination is provided, all of its elements (for arrays) or properties (for objects) 950 * are deleted and then all elements/properties from the source are copied to it. 951 * * If `source` is not an object or array (inc. `null` and `undefined`), `source` is returned. 952 * * If `source` is identical to `destination` an exception will be thrown. 953 * 954 * <br /> 955 * <div class="alert alert-warning"> 956 * Only enumerable properties are taken into account. Non-enumerable properties (both on `source` 957 * and on `destination`) will be ignored. 958 * </div> 959 * 960 * @param {*} source The source that will be used to make a copy. 961 * Can be any type, including primitives, `null`, and `undefined`. 962 * @param {(Object|Array)=} destination Destination into which the source is copied. If 963 * provided, must be of the same type as `source`. 964 * @returns {*} The copy or updated `destination`, if `destination` was specified. 965 * 966 * @example 967 <example module="copyExample" name="angular-copy"> 968 <file name="index.html">
969 <div ng-controller="ExampleController"> 970 <form novalidate class="simple-form"> 971 <label>Name: <input type="text" ng-model="user.name" /></label><br /> 972 <label>Age: <input type="number" ng-model="user.age" /></label><br /> 973 Gender: <label><input type="radio" ng-model="user.gender" value="male" />male</label> 974 <label><input type="radio" ng-model="user.gender" value="female" />female</label><br /> 975 <button ng-click="reset()">RESET</button> 976 <button ng-click="update(user)">SAVE</button> 977 </form> 978 <pre>form = {{user | json}}</pre> 979 <pre>master = {{master | json}}</pre> 980 </div> 981 </file> 982 <file name="script.js"> 983 // Module: copyExample 984 angular. 985 module('copyExample', []). 986 controller('ExampleController', ['$scope', function($scope) { 987 $scope.master = {}; 988 989 $scope.reset = function() { 990 // Example with 1 argument 991 $scope.user = angular.copy($scope.master); 992 }; 993 994 $scope.update = function(user) { 995 // Example with 2 arguments 996 angular.copy(user, $scope.mast
vendor: 9,464 bytes, lines 996-1307
996er); 997 }; 998 999 $scope.reset(); 1000 }]); 1001 </file> 1002 </example> 1003 */ 1004function copy(source, destination, maxDepth) { 1005 var stackSource = []; 1006 var stackDest = []; 1007 maxDepth = isValidObjectMaxDepth(maxDepth) ? maxDepth : NaN; 1008 1009 if (destination) { 1010 if (isTypedArray(destination) || isArrayBuffer(destination)) { 1011 throw ngMinErr('cpta', 'Can\'t copy! TypedArray destination cannot be mutated.'); 1012 } 1013 if (source === destination) { 1014 throw ngMinErr('cpi', 'Can\'t copy! Source and destination are identical.'); 1015 } 1016 1017 // Empty the destination object 1018 if (isArray(destination)) { 1019 destination.length = 0; 1020 } else { 1021 forEach(destination, function(value, key) { 1022 if (key !== '$$hashKey') { 1023 delete destination[key]; 1024 } 1025 }); 1026 } 1027 1028 stackSource.push(source); 1029 stackDest.push(destination); 1030 return copyRecurse(source, destination, maxDepth); 1031 } 1032 1033 return copyElement(source, maxDepth); 1034 1035 function copyRecurse(source, destination, maxDepth) { 1036 maxDepth--; 1037 if (maxDepth < 0) { 1038 return '...'; 1039 } 1040 var h = destination.$$hashKey; 1041 var key; 1042 if (isArray(source)) { 1043 for (var i = 0, ii = source.length; i < ii; i++) { 1044 destination.push(copyElement(source[i], maxDepth)); 1045 } 1046 } else if (isBlankObject(source)) { 1047 // createMap() fast path --- Safe to avoid hasOwnProperty check because prototype chain is empty 1048 for (key in source) { 1049 destination[key] = copyElement(source[key], maxDepth); 1050 } 1051 } else if (source && typeof source.hasOwnProperty === 'function') { 1052 // Slow path, which must rely on hasOwnProperty 1053 for (key in source) { 1054 if (source.hasOwnProperty(key)) { 1055 destination[key] = copyElement(source[key], maxDepth); 1056 } 1057 } 1058 } else { 1059 // Slowest path --- hasOwnProperty can't be called as a method 1060 for (key in source) { 1061 if (hasOwnProperty.call(source, key)) { 1062 destination[key] = copyElement(source[key], maxDepth); 1063 } 1064 } 1065 } 1066 setHashKey(destination, h); 1067 return destination; 1068 } 1069 1070 function copyElement(source, maxDepth) { 1071 // Simple values 1072 if (!isObject(source)) { 1073 return source; 1074 } 1075 1076 // Already copied values 1077 var index = stackSource.indexOf(source); 1078 if (index !== -1) { 1079 return stackDest[index]; 1080 } 1081 1082 if (isWindow(source) || isScope(source)) { 1083 throw ngMinErr('cpws', 1084 'Can\'t copy! Making copies of Window or Scope instances is not supported.'); 1085 } 1086 1087 var needsRecurse = false; 1088 var destination = copyType(source); 1089 1090 if (destination === undefined) { 1091 destination = isArray(source) ? [] : Object.create(getPrototypeOf(source)); 1092 needsRecurse = true; 1093 } 1094 1095 stackSource.push(source); 1096 stackDest.push(destination); 1097 1098 return needsRecurse 1099 ? copyRecurse(source, destination, maxDepth) 1100 : destination; 1101 } 1102 1103 function copyType(source) { 1104 switch (toString.call(source)) { 1105 case '[object Int8Array]': 1106 case '[object Int16Array]': 1107 case '[object Int32Array]': 1108 case '[object Float32Array]': 1109 case '[object Float64Array]': 1110 case '[object Uint8Array]': 1111 case '[object Uint8ClampedArray]': 1112 case '[object Uint16Array]': 1113 case '[object Uint32Array]': 1114 return new source.constructor(copyElement(source.buffer), source.byteOffset, source.length); 1115 1116 case '[object ArrayBuffer]': 1117 // Support: IE10 1118 if (!source.slice) { 1119 // If we're in this case we know the environment supports ArrayBuffer 1120 /* eslint-disable no-undef */ 1121 var copied = new ArrayBuffer(source.byteLength); 1122 new Uint8Array(copied).set(new Uint8Array(source)); 1123 /* eslint-enable */ 1124 return copied; 1125 } 1126 return source.slice(0); 1127 1128 case '[object Boolean]': 1129 case '[object Number]': 1130 case '[object String]': 1131 case '[object Date]': 1132 return new source.constructor(source.valueOf()); 1133 1134 case '[object RegExp]': 1135 var re = new RegExp(source.source, source.toString().match(/[^/]*$/)[0]); 1136 re.lastIndex = source.lastIndex; 1137 return re; 1138 1139 case '[object Blob]': 1140 return new source.constructor([source], {type: source.type}); 1141 } 1142 1143 if (isFunction(source.cloneNode)) { 1144 return source.cloneNode(true); 1145 } 1146 } 1147} 1148 1149 1150// eslint-disable-next-line no-self-compare 1151function simpleCompare(a, b) { return a === b || (a !== a && b !== b); } 1152 1153 1154/** 1155 * @ngdoc function 1156 * @name angular.equals 1157 * @module ng 1158 * @kind function 1159 * 1160 * @description 1161 * Determines if two objects or two values are equivalent. Supports value types, regular 1162 * expressions, arrays and objects. 1163 * 1164 * Two objects or values are considered equivalent if at least one of the following is true: 1165 * 1166 * * Both objects or values pass `===` comparison. 1167 * * Both objects or values are of the same type and all of their properties are equal by 1168 * comparing them with `angular.equals`. 1169 * * Both values are NaN. (In JavaScript, NaN == NaN => false. But we consider two NaN as equal) 1170 * * Both values represent the same regular expression (In JavaScript, 1171 * /abc/ == /abc/ => false. But we consider two regular expressions as equal when their textual 1172 * representation matches). 1173 * 1174 * During a property comparison, properties of `function` type and properties with names 1175 * that begin with `$` are ignored. 1176 * 1177 * Scope and DOMWindow objects are being compared only by identify (`===`). 1178 * 1179 * @param {*} o1 Object or value to compare. 1180 * @param {*} o2 Object or value to compare. 1181 * @returns {boolean} True if arguments are equal. 1182 * 1183 * @example 1184 <example module="equalsExample" name="equalsExample"> 1185 <file name="index.html"> 1186 <div ng-controller="ExampleController"> 1187 <form novalidate> 1188 <h3>User 1</h3> 1189 Name: <input type="text" ng-model="user1.name"> 1190 Age: <input type="number" ng-model="user1.age"> 1191 1192 <h3>User 2</h3> 1193 Name: <input type="text" ng-model="user2.name"> 1194 Age: <input type="number" ng-model="user2.age"> 1195 1196 <div> 1197 <br/> 1198 <input type="button" value="Compare" ng-click="compare()"> 1199 </div> 1200 User 1: <pre>{{user1 | json}}</pre> 1201 User 2: <pre>{{user2 | json}}</pre> 1202 Equal: <pre>{{result}}</pre> 1203 </form> 1204 </div> 1205 </file> 1206 <file name="script.js"> 1207 angular.module('equalsExample', []).controller('ExampleController', ['$scope', function($scope) { 1208 $scope.user1 = {}; 1209 $scope.user2 = {}; 1210 $scope.compare = function() { 1211 $scope.result = angular.equals($scope.user1, $scope.user2); 1212 }; 1213 }]); 1214 </file> 1215 </example> 1216 */ 1217function equals(o1, o2) { 1218 if (o1 === o2) return true; 1219 if (o1 === null || o2 === null) return false; 1220 // eslint-disable-next-line no-self-compare 1221 if (o1 !== o1 && o2 !== o2) return true; // NaN === NaN 1222 var t1 = typeof o1, t2 = typeof o2, length, key, keySet; 1223 if (t1 === t2 && t1 === 'object') { 1224 if (isArray(o1)) { 1225 if (!isArray(o2)) return false; 1226 if ((length = o1.length) === o2.length) { 1227 for (key = 0; key < length; key++) { 1228 if (!equals(o1[key], o2[key])) return false; 1229 } 1230 return true; 1231 } 1232 } else if (isDate(o1)) { 1233 if (!isDate(o2)) return false; 1234 return simpleCompare(o1.getTime(), o2.getTime()); 1235 } else if (isRegExp(o1)) { 1236 if (!isRegExp(o2)) return false; 1237 return o1.toString() === o2.toString(); 1238 } else { 1239 if (isScope(o1) || isScope(o2) || isWindow(o1) || isWindow(o2) || 1240 isArray(o2) || isDate(o2) || isRegExp(o2)) return false; 1241 keySet = createMap(); 1242 for (key in o1) { 1243 if (key.charAt(0) === '$' || isFunction(o1[key])) continue; 1244 if (!equals(o1[key], o2[key])) return false; 1245 keySet[key] = true; 1246 } 1247 for (key in o2) { 1248 if (!(key in keySet) && 1249 key.charAt(0) !== '$' && 1250 isDefined(o2[key]) && 1251 !isFunction(o2[key])) return false; 1252 } 1253 return true; 1254 } 1255 } 1256 return false; 1257} 1258 1259var csp = function() { 1260 if (!isDefined(csp.rules)) { 1261 1262 1263 var ngCspElement = (window.document.querySelector('[ng-csp]') || 1264 window.document.querySelector('[data-ng-csp]')); 1265 1266 if (ngCspElement) { 1267 var ngCspAttribute = ngCspElement.getAttribute('ng-csp') || 1268 ngCspElement.getAttribute('data-ng-csp'); 1269 csp.rules = { 1270 noUnsafeEval: !ngCspAttribute || (ngCspAttribute.indexOf('no-unsafe-eval') !== -1), 1271 noInlineStyle: !ngCspAttribute || (ngCspAttribute.indexOf('no-inline-style') !== -1) 1272 }; 1273 } else { 1274 csp.rules = { 1275 noUnsafeEval: noUnsafeEval(), 1276 noInlineStyle: false 1277 }; 1278 } 1279 } 1280 1281 return csp.rules; 1282 1283 function noUnsafeEval() { 1284 try { 1285 // eslint-disable-next-line no-new, no-new-func 1286 new Function(''); 1287 return false; 1288 } catch (e) { 1289 return true; 1290 } 1291 } 1292}; 1293 1294/** 1295 * @ngdoc directive 1296 * @module ng 1297 * @name ngJq 1298 * 1299 * @element ANY 1300 * @param {string=} ngJq the name of the library available under `window` 1301 * to be used for angular.element 1302 * @description 1303 * Use this directive to force the angular.element library. This should be 1304 * used to force either jqLite by leaving ng-jq blank or setting the name of 1305 * the jquery variable under window (eg. jQuery). 1306 * 1307 * Since
1307angular looks for this directive when it is loaded (doesn't wait for the 1308 * DOMContentLoaded event), it must be placed on an element that comes before the script 1309 * which loads angular. Also, only the first instance of `ng-jq` will be used and all 1310 * others ignored. 1311 * 1312 * @example 1313 * This example shows how to force jqLite using the `ngJq` directive to the `html` tag. 1314 ```html 1315 <!doctype html> 1316 <html ng-app ng-jq> 1317 ... 1318 ... 1319 </html> 1320 ``` 1321 * @example 1322 * This example shows how to use a jQuery based library of a different name. 1323 * The library name must be available at the top most 'window'. 1324 ```html 1325 <!doctype html> 1326 <html ng-app ng-jq="jQueryLib"> 1327 ... 1328 ... 1329 </html> 1330 ``` 1331 */ 1332var jq = function() { 1333 if (isDefined(jq.name_)) return jq.name_; 1334 var el; 1335 var i, ii = ngAttrPrefixes.length, prefix, name; 1336 for (i = 0; i < ii; ++i) { 1337 prefix = ngAttrPrefixes[i]; 1338 el = window.document.querySelector('[' + prefix.replace(':', '\\:') + 'jq]'); 1339 if (el) { 1340 name = el.getAttribute(prefix + 'jq'); 1341 break; 1342 } 1343 } 1344 1345 return (jq.name_ = name); 1346}; 1347 1348function concat(array1, array2, index) { 1349 return array1.concat(slice.call(array2, index)); 1350} 1351 1352function sliceArgs(args, startIndex) { 1353 return slice.call(args, startIndex || 0); 1354} 1355 1356 1357/** 1358 * @ngdoc function 1359 * @name angular.bind 1360 * @module ng 1361 * @kind function 1362 * 1363 * @description 1364 * Returns a function which calls function `fn` bound to `self` (`self` becomes the `this` for 1365 * `fn`). You can supply optional `args` that are prebound to the function. This feature is also 1366 * known as [partial application](http://en.wikipedia.org/wiki/Partial_application), as 1367 * distinguished from [function currying](http://en.wikipedia.org/wiki/Currying#Contrast_with_partial_function_application). 1368 * 1369 * @param {Object} self Context which `fn` should be evaluated in. 1370 * @param {function()} fn Function to be bound. 1371 * @param {...*} args Optional arguments to be prebound to the `fn` function call. 1372 * @returns {function()} Function that wraps the `fn` with all the specified bindings. 1373 */ 1374function bind(self, fn) { 1375 var curryArgs = arguments.length > 2 ? sliceArgs(arguments, 2) : []; 1376 if (isFunction(fn) && !(fn instanceof RegExp)) { 1377 return curryArgs.length 1378 ? function() { 1379 return arguments.length 1380 ? fn.apply(self, concat(curryArgs, arguments, 0)) 1381 : fn.apply(self, curryArgs); 1382 } 1383 : function() { 1384 return arguments.length 1385 ? fn.apply(self, arguments) 1386 : fn.call(self); 1387 }; 1388 } else { 1389 // In IE, native methods are not functions so they cannot be bound (note: they don't need to be). 1390 return fn; 1391 } 1392} 1393 1394 1395function toJsonReplacer(key, value) { 1396 var val = value; 1397 1398 if (typeof key === 'string' && key.charAt(0) === '$' && key.charAt(1) === '$') { 1399 val = undefined; 1400 } else if (isWindow(value)) { 1401 val = '$WINDOW'; 1402 } else if (value && window.document === value) { 1403 val = '$DOCUMENT'; 1404 } else if (isScope(value)) { 1405 val = '$SCOPE'; 1406 } 1407 1408 return val; 1409} 1410 1411 1412/** 1413 * @ngdoc function 1414 * @name angular.toJson 1415 * @module ng 1416 * @kind function 1417 * 1418 * @description 1419 * Serializes input into a JSON-formatted string. Properties with leading $$ characters will be 1420 * stripped since angular uses this notation internally. 1421 * 1422 * @param {Object|Array|Date|string|number|boolean} obj Input to be serialized into JSON. 1423 * @param {boolean|number}
vendor: 8,566 bytes, lines 1423-1701
1423 [pretty=2] If set to true, the JSON output will contain newlines and whitespace. 1424 * If set to an integer, the JSON output will contain that many spaces per indentation. 1425 * @returns {string|undefined} JSON-ified string representing `obj`. 1426 * @knownIssue 1427 * 1428 * The Safari browser throws a `RangeError` instead of returning `null` when it tries to stringify a `Date` 1429 * object with an invalid date value. The only reliable way to prevent this is to monkeypatch the 1430 * `Date.prototype.toJSON` method as follows: 1431 * 1432 * ``` 1433 * var _DatetoJSON = Date.prototype.toJSON; 1434 * Date.prototype.toJSON = function() { 1435 * try { 1436 * return _DatetoJSON.call(this); 1437 * } catch(e) { 1438 * if (e instanceof RangeError) { 1439 * return null; 1440 * } 1441 * throw e; 1442 * } 1443 * }; 1444 * ``` 1445 * 1446 * See https://github.com/angular/angular.js/pull/14221 for more information. 1447 */ 1448function toJson(obj, pretty) { 1449 if (isUndefined(obj)) return undefined; 1450 if (!isNumber(pretty)) { 1451 pretty = pretty ? 2 : null; 1452 } 1453 return JSON.stringify(obj, toJsonReplacer, pretty); 1454} 1455 1456 1457/** 1458 * @ngdoc function 1459 * @name angular.fromJson 1460 * @module ng 1461 * @kind function 1462 * 1463 * @description 1464 * Deserializes a JSON string. 1465 * 1466 * @param {string} json JSON string to deserialize. 1467 * @returns {Object|Array|string|number} Deserialized JSON string. 1468 */ 1469function fromJson(json) { 1470 return isString(json) 1471 ? JSON.parse(json) 1472 : json; 1473} 1474 1475 1476var ALL_COLONS = /:/g; 1477function timezoneToOffset(timezone, fallback) { 1478 // Support: IE 9-11 only, Edge 13-15+ 1479 // IE/Edge do not "understand" colon (`:`) in timezone 1480 timezone = timezone.replace(ALL_COLONS, ''); 1481 var requestedTimezoneOffset = Date.parse('Jan 01, 1970 00:00:00 ' + timezone) / 60000; 1482 return isNumberNaN(requestedTimezoneOffset) ? fallback : requestedTimezoneOffset; 1483} 1484 1485 1486function addDateMinutes(date, minutes) { 1487 date = new Date(date.getTime()); 1488 date.setMinutes(date.getMinutes() + minutes); 1489 return date; 1490} 1491 1492 1493function convertTimezoneToLocal(date, timezone, reverse) { 1494 reverse = reverse ? -1 : 1; 1495 var dateTimezoneOffset = date.getTimezoneOffset(); 1496 var timezoneOffset = timezoneToOffset(timezone, dateTimezoneOffset); 1497 return addDateMinutes(date, reverse * (timezoneOffset - dateTimezoneOffset)); 1498} 1499 1500 1501/** 1502 * @returns {string} Returns the string representation of the element. 1503 */ 1504function startingTag(element) { 1505 element = jqLite(element).clone().empty(); 1506 var elemHtml = jqLite('<div>').append(element).html(); 1507 try { 1508 return element[0].nodeType === NODE_TYPE_TEXT ? lowercase(elemHtml) : 1509 elemHtml. 1510 match(/^(<[^>]+>)/)[1]. 1511 replace(/^<([\w-]+)/, function(match, nodeName) {return '<' + lowercase(nodeName);}); 1512 } catch (e) { 1513 return lowercase(elemHtml); 1514 } 1515 1516} 1517 1518 1519///////////////////////////////////////////////// 1520 1521/** 1522 * Tries to decode the URI component without throwing an exception. 1523 * 1524 * @private 1525 * @param str value potential URI component to check. 1526 * @returns {boolean} True if `value` can be decoded 1527 * with the decodeURIComponent function. 1528 */ 1529function tryDecodeURIComponent(value) { 1530 try { 1531 return decodeURIComponent(value); 1532 } catch (e) { 1533 // Ignore any invalid uri component. 1534 } 1535} 1536 1537 1538/** 1539 * Parses an escaped url query string into key-value pairs. 1540 * @returns {Object.<string,boolean|Array>} 1541 */ 1542function parseKeyValue(/**string*/keyValue) { 1543 var obj = {}; 1544 forEach((keyValue || '').split('&'), function(keyValue) { 1545 var splitPoint, key, val; 1546 if (keyValue) { 1547 key = keyValue = keyValue.replace(/\+/g,'%20'); 1548 splitPoint = keyValue.indexOf('='); 1549 if (splitPoint !== -1) { 1550 key = keyValue.substring(0, splitPoint); 1551 val = keyValue.substring(splitPoint + 1); 1552 } 1553 key = tryDecodeURIComponent(key); 1554 if (isDefined(key)) { 1555 val = isDefined(val) ? tryDecodeURIComponent(val) : true; 1556 if (!hasOwnProperty.call(obj, key)) { 1557 obj[key] = val; 1558 } else if (isArray(obj[key])) { 1559 obj[key].push(val); 1560 } else { 1561 obj[key] = [obj[key],val]; 1562 } 1563 } 1564 } 1565 }); 1566 return obj; 1567} 1568 1569function toKeyValue(obj) { 1570 var parts = []; 1571 forEach(obj, function(value, key) { 1572 if (isArray(value)) { 1573 forEach(value, function(arrayValue) { 1574 parts.push(encodeUriQuery(key, true) + 1575 (arrayValue === true ? '' : '=' + encodeUriQuery(arrayValue, true))); 1576 }); 1577 } else { 1578 parts.push(encodeUriQuery(key, true) + 1579 (value === true ? '' : '=' + encodeUriQuery(value, true))); 1580 } 1581 }); 1582 return parts.length ? parts.join('&') : ''; 1583} 1584 1585 1586/** 1587 * We need our custom method because encodeURIComponent is too aggressive and doesn't follow 1588 * http://www.ietf.org/rfc/rfc3986.txt with regards to the character set (pchar) allowed in path 1589 * segments: 1590 * segment = *pchar 1591 * pchar = unreserved / pct-encoded / sub-delims / ":" / "@" 1592 * pct-encoded = "%" HEXDIG HEXDIG 1593 * unreserved = ALPHA / DIGIT / "-" / "." / "_" / "~" 1594 * sub-delims = "!" / "$" / "&" / "'" / "(" / ")" 1595 * / "*" / "+" / "," / ";" / "=" 1596 */ 1597function encodeUriSegment(val) { 1598 return encodeUriQuery(val, true). 1599 replace(/%26/gi, '&'). 1600 replace(/%3D/gi, '='). 1601 replace(/%2B/gi, '+'); 1602} 1603 1604 1605/** 1606 * This method is intended for encoding *key* or *value* parts of query component. We need a custom 1607 * method because encodeURIComponent is too aggressive and encodes stuff that doesn't have to be 1608 * encoded per http://tools.ietf.org/html/rfc3986: 1609 * query = *( pchar / "/" / "?" ) 1610 * pchar = unreserved / pct-encoded / sub-delims / ":" / "@" 1611 * unreserved = ALPHA / DIGIT / "-" / "." / "_" / "~" 1612 * pct-encoded = "%" HEXDIG HEXDIG 1613 * sub-delims = "!" / "$" / "&" / "'" / "(" / ")" 1614 * / "*" / "+" / "," / ";" / "=" 1615 */ 1616function encodeUriQuery(val, pctEncodeSpaces) { 1617 return encodeURIComponent(val). 1618 replace(/%40/gi, '@'). 1619 replace(/%3A/gi, ':'). 1620 replace(/%24/g, '$'). 1621 replace(/%2C/gi, ','). 1622 replace(/%3B/gi, ';'). 1623 replace(/%20/g, (pctEncodeSpaces ? '%20' : '+')); 1624} 1625 1626var ngAttrPrefixes = ['ng-', 'data-ng-', 'ng:', 'x-ng-']; 1627 1628function getNgAttribute(element, ngAttr) { 1629 var attr, i, ii = ngAttrPrefixes.length; 1630 for (i = 0; i < ii; ++i) { 1631 attr = ngAttrPrefixes[i] + ngAttr; 1632 if (isString(attr = element.getAttribute(attr))) { 1633 return attr; 1634 } 1635 } 1636 return null; 1637} 1638 1639function allowAutoBootstrap(document) { 1640 var script = document.currentScript; 1641 1642 if (!script) { 1643 // Support: IE 9-11 only 1644 // IE does not have `document.currentScript` 1645 return true; 1646 } 1647 1648 // If the `currentScript` property has been clobbered just return false, since this indicates a probable attack 1649 if (!(script instanceof window.HTMLScriptElement || script instanceof window.SVGScriptElement)) { 1650 return false; 1651 } 1652 1653 var attributes = script.attributes; 1654 var srcs = [attributes.getNamedItem('src'), attributes.getNamedItem('href'), attributes.getNamedItem('xlink:href')]; 1655 1656 return srcs.every(function(src) { 1657 if (!src) { 1658 return true; 1659 } 1660 if (!src.value) { 1661 return false; 1662 } 1663 1664 var link = document.createElement('a'); 1665 link.href = src.value; 1666 1667 if (document.location.origin === link.origin) { 1668 // Same-origin resources are always allowed, even for non-whitelisted schemes. 1669 return true; 1670 } 1671 // Disabled bootstrapping unless angular.js was loaded from a known scheme used on the web. 1672 // This is to prevent angular.js bundled with browser extensions from being used to bypass the 1673 // content security policy in web pages and other browser extensions. 1674 switch (link.protocol) { 1675 case 'http:': 1676 case 'https:': 1677 case 'ftp:': 1678 case 'blob:': 1679 case 'file:': 1680 case 'data:': 1681 return true; 1682 default: 1683 return false; 1684 } 1685 }); 1686} 1687 1688// Cached as it has to run during loading so that document.currentScript is available. 1689var isAutoBootstrapAllowed = allowAutoBootstrap(window.document); 1690 1691/** 1692 * @ngdoc directive 1693 * @name ngApp 1694 * @module ng 1695 * 1696 * @element ANY 1697 * @param {angular.Module} ngApp an optional application 1698 * {@link angular.module module} name to load. 1699 * @param {boolean=} ngStrictDi if this attribute is present on the app element, the injector will be 1700 * created in "strict-di" mode. This means that the application will fail to invoke functions which 1701 * do not use explicit function annotation (and are thus unsuitable for minification), as de
1701scribed 1702 * in {@link guide/di the Dependency Injection guide}, and useful debugging info will assist in 1703 * tracking down the root of these bugs. 1704 * 1705 * @description 1706 * 1707 * Use this directive to **auto-bootstrap** an AngularJS application. The `ngApp` directive 1708 * designates the **root element** of the application and is typically placed near the root element 1709 * of the page - e.g. on the `<body>` or `<html>` tags. 1710 * 1711 * There are a few things to keep in mind when using `ngApp`: 1712 * - only one AngularJS application can be auto-bootstrapped per HTML document. The first `ngApp` 1713 * found in the document will be used to define the root element to auto-bootstrap as an 1714 * application. To run multiple applications in an HTML document you must manually bootstrap them using 1715 * {@link angular.bootstrap} instead. 1716 * - AngularJS applications cannot be nested within each other. 1717 * - Do not use a directive that uses {@link ng.$compile#transclusion transclusion} on the same element as `ngApp`. 1718 * This includes directives such as {@link ng.ngIf `ngIf`}, {@link ng.ngInclude `ngInclude`} and 1719 * {@link ngRoute.ngView `ngView`}. 1720 * Doing this misplaces the app {@link ng.$rootElement `$rootElement`} and the app's {@link auto.$injector injector}, 1721 * causing animations to stop working and making the injector inaccessible from outside the app. 1722 * 1723 * You can specify an **AngularJS module** to be used as the root module for the application. This 1724 * module will be loaded into the {@link auto.$injector} when the application is bootstrapped. It 1725 * should contain the application code needed or have dependencies on other modules that will 1726 * contain the code. See {@link angular.module} for more information. 1727 * 1728 * In the example below if the `ngApp` directive were not placed on the `html` element then the 1729 * document would not be compiled, the `AppController` would not be instantiated and the `{{ a+b }}` 1730 * would not be resolved to `3`. 1731 * 1732 * `ngApp` is the easiest, and most common way to bootstrap an application. 1733 * 1734 <example module="ngAppDemo" name="ng-app"> 1735 <file name="index.html"> 1736 <div ng-controller="ngAppDemoController"> 1737 I can add: {{a}} + {{b}} = {{ a+b }} 1738 </div> 1739 </file> 1740 <file name="script.js"> 1741 angular.module('ngAppDemo', []).controller('ngAppDemoController', function($scope) { 1742 $scope.a = 1; 1743 $scope.b = 2; 1744 }); 1745 </file> 1746 </example> 1747 * 1748 * Using `ngStrictDi`, you would see something like this: 1749 * 1750 <example ng-app-included="true" name="strict-di"> 1751 <file name="index.html"> 1752 <div ng-app="ngAppStrictDemo" ng-strict-di> 1753 <div ng-controller="GoodController1"> 1754 I can add: {{a}} + {{b}} = {{ a+b }} 1755 1756 <p>This renders because the controller does not fail to 1757 instantiate, by using explicit annotation style (see 1758 script.js for details) 1759 </p> 1760 </div> 1761 1762 <div ng-controller="GoodController2"> 1763 Name: <input ng-model="name"><br /> 1764 Hello, {{name}}! 1765 1766 <p>This renders because the controller does not fail to 1767 instantiate, by using explicit annotation style 1768 (see script.js for details) 1769 </p> 1770 </div> 1771 1772 <div ng-controller="BadController"> 1773 I can add: {{a}} + {{b}} = {{ a+b }} 1774 1775 <p>The controller could not be instantiated, due to relying 1776 on automatic function annotations (which are disabled in 1777 strict mode). As such, the content of this section is not 1778 interpolated, and there should be an error in your web console. 1779 </p> 1780 </div> 1781 </div> 1782 </file> 1783 <file name="script.js"> 1784 angular.module('ngAppStrictDemo', []) 1785 // BadController will fail to instantiate, due to relying on automatic function annotation, 1786 // rather than an explicit annotation 1787 .controller('BadController', function($scope) { 1788 $scope.a = 1; 1789 $scope.b = 2; 1790 }) 1791 // Unlike BadController, GoodController1 and GoodController2 will not fail to be instantiated, 1792 // due to using explicit annotations using the array style and $inject property, respectively. 1793 .controller('GoodController1', ['$scope', function($scope) { 1794 $scope.a = 1; 1795 $scope.b = 2; 1796 }]) 1797 .controller('GoodController2', GoodController2); 1798 function GoodController2($scope) { 1799 $scope.name = 'World'; 1800 } 1801 GoodController2.$inject = ['$scope']; 1802 </file> 1803 <file name="style.css"> 1804 div[ng-controller] { 1805 margin-bottom: 1em; 1806 -webkit-border-radius: 4px; 1807 border-radius: 4px; 1808 border: 1px solid; 1809 padding: .5em; 1810 } 1811 div[ng-controller^=Good] { 1812 border-color: #d6e9c6; 1813 background-color: #dff0d8; 1814 color: #3c763d; 1815 } 1816 div[ng-controller^=Bad] { 1817 border-color: #ebccd1; 1818 background-color: #f2dede; 1819 color: #a94442; 1820 margin-bottom: 0; 1821 } 1822 </file> 1823 </example> 1824 */ 1825function angularInit(element, bootstrap) { 1826 var appElement, 1827 module, 1828 config = {}; 1829 1830 // The element `element` has priority over any other element. 1831 forEach(ngAttrPrefixes, function(prefix) { 1832 var name = prefix + 'app'; 1833 1834 if (!appElement && element.hasAttribute && element.hasAttribute(name)) { 1835 appElement = element; 1836 module = element.getAttribute(name); 1837 } 1838 }); 1839 forEach(ngAttrPrefixes, function(prefix) { 1840 var name = prefix + 'app'; 1841 var candidate; 1842 1843 if (!appElement && (candidate = element.querySelector('[' + name.replace(':', '\\:') + ']'))) { 1844 appElement = candidate; 1845 module = candidate.getAttribute(name); 1846 } 1847 }); 1848 if (appElement) { 1849 if (!isAutoBootstrapAllowed) { 1850 window.console.error('Angular: disabling automatic bootstrap. <script> protocol indicates ' + 1851 'an extension, document.location.href does not match.'); 1852 return; 1853 } 1854 config.strictDi = getNgAttribute(appElement, 'strict-di') !== null; 1855 bootstrap(appElement, module ? [module] : [], config); 1856 } 1857} 1858 1859/** 1860 * @ngdoc function 1861 * @name angular.bootstrap 1862 * @module ng 1863 * @description 1864 * Use this function to manually start up angular application. 1865 * 1866 * For more information, see the {@link guide/bootstrap Bootstrap guide}. 1867 * 1868 * Angular will detect if it has been loaded into the browser more than once and only allow the 1869 * first loaded script to be bootstrapped and will report a warning to the browser console for 1870 * each of the subsequent scripts. This prevents strange results in applications, where otherwise 1871 * multiple instances of Angular try to work on the DOM. 1872 * 1873 * <div class="alert alert-warning">
1874 * **Note:** Protractor based end-to-end tests cannot use this function to bootstrap manually. 1875 * They must use {@link ng.directive:ngApp ngApp}. 1876 * </div> 1877 * 1878 * <div class="alert alert-warning"> 1879 * **Note:** Do not bootstrap the app on an element with a directive that uses {@link ng.$compile#transclusion transclusion}, 1880 * such as {@link ng.ngIf `ngIf`}, {@link ng.ngInclude `ngInclude`} and {@link ngRoute.ngView `ngView`}. 1881 * Doing this misplaces the app {@link ng.$rootElement `$rootElement`} and the app's {@link auto.$injector injector}, 1882 * causing animations to stop working and making the injector inaccessible from outside the app. 1883 * </div> 1884 * 1885 * ```html 1886 * <!doctype html> 1887 * <html> 1888 * <body> 1889 * <div ng-controller="WelcomeController"> 1890 * {{greeting}} 1891 * </div> 1892 * 1893 * <script src="angular.js"></script> 1894 * <script> 1895 * var app = angular.module('demo', []) 1896 * .controller('WelcomeController', function($scope) { 1897 * $scope.greeting = 'Welcome!'; 1898 * }); 1899 * angular.bootstrap(document, ['demo']); 1900 * </script> 1901 * </body> 1902 * </html> 1903 * ``` 1904 * 1905 * @param {DOMElement} element DOM element which is the root of angular application. 1906 * @param {Array<String|Function|Array>=} modules an array of modules to load into the application. 1907 * Each item in the array should be the name of a predefined module or a (DI annotated) 1908 * function that will be invoked by the injector as a `config` block. 1909 * See: {@link angular.module modules} 1910 * @param {Object=} config an object for defining configuration options for the application. The 1911 * following keys are supported: 1912 * 1913 * * `strictDi` - disable automatic function annotation for the application. This is meant to 1914 * assist in finding bugs which break minified code. Defaults to `false`. 1915 * 1916 * @returns {auto.$injector} Returns the newly created injector for this app. 1917 */ 1918function bootstrap(element, modules, config) { 1919 if (!isObject(config)) config = {}; 1920 var defaultConfig = { 1921 strictDi: false 1922 }; 1923 config = extend(defaultConfig, config); 1924 var doBootstrap = function() { 1925 element = jqLite(element); 1926 1927 if (element.injector()) { 1928 var tag = (element[0] === window.document) ? 'document' : startingTag(element); 1929 // Encode angle brackets to prevent input from being sanitized to empty string #8683. 1930 throw ngMinErr( 1931 'btstrpd', 1932 'App already bootstrapped with this element \'{0}\'', 1933 tag.replace(/</,'<').replace(/>/,'>')); 1934 } 1935 1936 modules = modules || []; 1937 modules.unshift(['$provide', function($provide) { 1938 $provide.value('$rootElement', element); 1939 }]); 1940 1941 if (config.debugInfoEnabled) { 1942 // Pushing so that this overrides `debugInfoEnabled` setting defined in user's `modules`. 1943 modules.push(['$compileProvider', function($compileProvider) { 1944 $compileProvider.debugInfoEnabled(true); 1945 }]); 1946 } 1947 1948 modules.unshift('ng'); 1949 var injector = createInjector(modules, config.strictDi); 1950 injector.invoke(['$rootScope', '$rootElement', '$compile', '$injector', 1951 function bootstrapApply(scope, element, compile, injector) { 1952 scope.$apply(function() { 1953 element.data('$injector', injector); 1954 compile(element)(scope); 1955 }); 1956 }] 1957 ); 1958 return injector; 1959 }; 1960 1961 var NG_ENABLE_DEBUG_INFO = /^NG_ENABLE_DEBUG_INFO!/; 1962 var NG_DEFER_BOOTSTRAP = /^NG_DEFER_BOOTSTRAP!/; 1963 1964 if (window && NG_ENABLE_DEBUG_INFO.test(window.name)) { 1965 config.debugInfoEnabled = true; 1966 window.name = window.name.replace(NG_ENABLE_DEBUG_INFO, ''); 1967 } 1968 1969 if (window && !NG_DEFER_BOOTSTRAP.test(window.name)) { 1970 return doBootstrap(); 1971 } 1972 1973 window.name = window.name.replace(NG_DEFER_BOOTSTRAP, ''); 1974 angular.resumeBootstrap = function(extraModules) { 1975 forEach(extraModules, function(module) { 1976 modules.push(module); 1977 }); 1978 return doBootstrap(); 1979 }; 1980 1981 if (isFunction(angular.resumeDeferredBootstrap)) { 1982 angular.resumeDeferredBootstrap(); 1983 } 1984} 1985 1986/** 1987 * @ngdoc function 1988 * @name angular.reloadWithDebugInfo 1989 * @module ng 1990 * @description 1991 * Use this function to reload the current application with debug information turned on. 1992 * This takes precedence over a call to `$compileProvider.debugInfoEnabled(false)`. 1993 * 1994 * See {@link ng.$compileProvider#debugInfoEnabled} for more. 1995 */ 1996function reloadWithDebugInfo() { 1997 window.name = 'NG_ENABLE_DEBUG_INFO!' + window.name; 1998 window.location.reload(); 1999} 2000 2001/** 2002 * @name angular.getTestability 2003 * @module ng 2004 * @description 2005 * Get the testability service for the instance of Angular on the given 2006 * element. 2007 * @param {DOMElement} element DOM element which is the root of angular application. 2008 */ 2009function getTestability(rootElement) { 2010 var injector = angular.element(rootElement).injector(); 2011 if (!injector) { 2012 throw ngMinErr('test', 2013 'no injector found for element argument to getTestability'); 2014 } 2015 return injector.get('$$testability'); 2016} 2017 2018var SNAKE_CASE_REGEXP = /[A-Z]/g; 2019function snake_case(name, separator) { 2020 separator = separator || '_'; 2021 return name.replace(SNAKE_CASE_REGEXP, function(letter, pos) { 2022 return (pos ? separator : '') + letter.toLowerCase(); 2023 }); 2024} 2025 2026var bindJQueryFired = false;
vendor: 9,918 bytes, lines 2027-2343
2027function bindJQuery() { 2028 var originalCleanData; 2029 2030 if (bindJQueryFired) { 2031 return; 2032 } 2033 2034 // bind to jQuery if present; 2035 var jqName = jq(); 2036 jQuery = isUndefined(jqName) ? window.jQuery : // use jQuery (if present) 2037 !jqName ? undefined : // use jqLite 2038 window[jqName]; // use jQuery specified by `ngJq` 2039 2040 // Use jQuery if it exists with proper functionality, otherwise default to us. 2041 // Angular 1.2+ requires jQuery 1.7+ for on()/off() support. 2042 // Angular 1.3+ technically requires at least jQuery 2.1+ but it may work with older 2043 // versions. It will not work for sure with jQuery <1.7, though. 2044 if (jQuery && jQuery.fn.on) { 2045 jqLite = jQuery; 2046 extend(jQuery.fn, { 2047 scope: JQLitePrototype.scope, 2048 isolateScope: JQLitePrototype.isolateScope, 2049 controller: /** @type {?} */ (JQLitePrototype).controller, 2050 injector: JQLitePrototype.injector, 2051 inheritedData: JQLitePrototype.inheritedData 2052 }); 2053 2054 // All nodes removed from the DOM via various jQuery APIs like .remove() 2055 // are passed through jQuery.cleanData. Monkey-patch this method to fire 2056 // the $destroy event on all removed nodes. 2057 originalCleanData = jQuery.cleanData; 2058 jQuery.cleanData = function(elems) { 2059 var events; 2060 for (var i = 0, elem; (elem = elems[i]) != null; i++) { 2061 events = jQuery._data(elem, 'events'); 2062 if (events && events.$destroy) { 2063 jQuery(elem).triggerHandler('$destroy'); 2064 } 2065 } 2066 originalCleanData(elems); 2067 }; 2068 } else { 2069 jqLite = JQLite; 2070 } 2071 2072 angular.element = jqLite; 2073 2074 // Prevent double-proxying. 2075 bindJQueryFired = true; 2076} 2077 2078/** 2079 * throw error if the argument is falsy. 2080 */ 2081function assertArg(arg, name, reason) { 2082 if (!arg) { 2083 throw ngMinErr('areq', 'Argument \'{0}\' is {1}', (name || '?'), (reason || 'required')); 2084 } 2085 return arg; 2086} 2087 2088function assertArgFn(arg, name, acceptArrayAnnotation) { 2089 if (acceptArrayAnnotation && isArray(arg)) { 2090 arg = arg[arg.length - 1]; 2091 } 2092 2093 assertArg(isFunction(arg), name, 'not a function, got ' + 2094 (arg && typeof arg === 'object' ? arg.constructor.name || 'Object' : typeof arg)); 2095 return arg; 2096} 2097 2098/** 2099 * throw error if the name given is hasOwnProperty 2100 * @param {String} name the name to test 2101 * @param {String} context the context in which the name is used, such as module or directive 2102 */ 2103function assertNotHasOwnProperty(name, context) { 2104 if (name === 'hasOwnProperty') { 2105 throw ngMinErr('badname', 'hasOwnProperty is not a valid {0} name', context); 2106 } 2107} 2108 2109/** 2110 * Return the value accessible from the object by path. Any undefined traversals are ignored 2111 * @param {Object} obj starting object 2112 * @param {String} path path to traverse 2113 * @param {boolean} [bindFnToScope=true] 2114 * @returns {Object} value as accessible by path 2115 */ 2116//TODO(misko): this function needs to be removed 2117function getter(obj, path, bindFnToScope) { 2118 if (!path) return obj; 2119 var keys = path.split('.'); 2120 var key; 2121 var lastInstance = obj; 2122 var len = keys.length; 2123 2124 for (var i = 0; i < len; i++) { 2125 key = keys[i]; 2126 if (obj) { 2127 obj = (lastInstance = obj)[key]; 2128 } 2129 } 2130 if (!bindFnToScope && isFunction(obj)) { 2131 return bind(lastInstance, obj); 2132 } 2133 return obj; 2134} 2135 2136/** 2137 * Return the DOM siblings between the first and last node in the given array. 2138 * @param {Array} array like object 2139 * @returns {Array} the inputted object or a jqLite collection containing the nodes 2140 */ 2141function getBlockNodes(nodes) { 2142 // TODO(perf): update `nodes` instead of creating a new object? 2143 var node = nodes[0]; 2144 var endNode = nodes[nodes.length - 1]; 2145 var blockNodes; 2146 2147 for (var i = 1; node !== endNode && (node = node.nextSibling); i++) { 2148 if (blockNodes || nodes[i] !== node) { 2149 if (!blockNodes) { 2150 blockNodes = jqLite(slice.call(nodes, 0, i)); 2151 } 2152 blockNodes.push(node); 2153 } 2154 } 2155 2156 return blockNodes || nodes; 2157} 2158 2159 2160/** 2161 * Creates a new object without a prototype. This object is useful for lookup without having to 2162 * guard against prototypically inherited properties via hasOwnProperty. 2163 * 2164 * Related micro-benchmarks: 2165 * - http://jsperf.com/object-create2 2166 * - http://jsperf.com/proto-map-lookup/2 2167 * - http://jsperf.com/for-in-vs-object-keys2 2168 * 2169 * @returns {Object} 2170 */ 2171function createMap() { 2172 return Object.create(null); 2173} 2174 2175function stringify(value) { 2176 if (value == null) { // null || undefined 2177 return ''; 2178 } 2179 switch (typeof value) { 2180 case 'string': 2181 break; 2182 case 'number': 2183 value = '' + value; 2184 break; 2185 default: 2186 if (hasCustomToString(value) && !isArray(value) && !isDate(value)) { 2187 value = value.toString(); 2188 } else { 2189 value = toJson(value); 2190 } 2191 } 2192 2193 return value; 2194} 2195 2196var NODE_TYPE_ELEMENT = 1; 2197var NODE_TYPE_ATTRIBUTE = 2; 2198var NODE_TYPE_TEXT = 3; 2199var NODE_TYPE_COMMENT = 8; 2200var NODE_TYPE_DOCUMENT = 9; 2201var NODE_TYPE_DOCUMENT_FRAGMENT = 11; 2202 2203/** 2204 * @ngdoc type 2205 * @name angular.Module 2206 * @module ng 2207 * @description 2208 * 2209 * Interface for configuring angular {@link angular.module modules}. 2210 */ 2211 2212function setupModuleLoader(window) { 2213 2214 var $injectorMinErr = minErr('$injector'); 2215 var ngMinErr = minErr('ng'); 2216 2217 function ensure(obj, name, factory) { 2218 return obj[name] || (obj[name] = factory()); 2219 } 2220 2221 var angular = ensure(window, 'angular', Object); 2222 2223 // We need to expose `angular.$$minErr` to modules such as `ngResource` that reference it during bootstrap 2224 angular.$$minErr = angular.$$minErr || minErr; 2225 2226 return ensure(angular, 'module', function() { 2227 /** @type {Object.<string, angular.Module>} */ 2228 var modules = {}; 2229 2230 /** 2231 * @ngdoc function 2232 * @name angular.module 2233 * @module ng 2234 * @description 2235 * 2236 * The `angular.module` is a global place for creating, registering and retrieving Angular 2237 * modules. 2238 * All modules (angular core or 3rd party) that should be available to an application must be 2239 * registered using this mechanism. 2240 * 2241 * Passing one argument retrieves an existing {@link angular.Module}, 2242 * whereas passing more than one argument creates a new {@link angular.Module} 2243 * 2244 * 2245 * # Module 2246 * 2247 * A module is a collection of services, directives, controllers, filters, and configuration information. 2248 * `angular.module` is used to configure the {@link auto.$injector $injector}. 2249 * 2250 * ```js 2251 * // Create a new module 2252 * var myModule = angular.module('myModule', []); 2253 * 2254 * // register a new service 2255 * myModule.value('appName', 'MyCoolApp'); 2256 * 2257 * // configure existing services inside initialization blocks. 2258 * myModule.config(['$locationProvider', function($locationProvider) { 2259 * // Configure existing providers 2260 * $locationProvider.hashPrefix('!'); 2261 * }]); 2262 * ``` 2263 * 2264 * Then you can create an injector and load your modules like this: 2265 * 2266 * ```js 2267 * var injector = angular.injector(['ng', 'myModule']) 2268 * ``` 2269 * 2270 * However it's more likely that you'll just use 2271 * {@link ng.directive:ngApp ngApp} or 2272 * {@link angular.bootstrap} to simplify this process for you. 2273 * 2274 * @param {!string} name The name of the module to create or retrieve. 2275 * @param {!Array.<string>=} requires If specified then new module is being created. If 2276 * unspecified then the module is being retrieved for further configuration. 2277 * @param {Function=} configFn Optional configuration function for the module. Same as 2278 * {@link angular.Module#config Module#config()}. 2279 * @returns {angular.Module} new module with the {@link angular.Module} api. 2280 */ 2281 return function module(name, requires, configFn) { 2282 2283 var info = {}; 2284 2285 var assertNotHasOwnProperty = function(name, context) { 2286 if (name === 'hasOwnProperty') { 2287 throw ngMinErr('badname', 'hasOwnProperty is not a valid {0} name', context); 2288 } 2289 }; 2290 2291 assertNotHasOwnProperty(name, 'module'); 2292 if (requires && modules.hasOwnProperty(name)) { 2293 modules[name] = null; 2294 } 2295 return ensure(modules, name, function() { 2296 if (!requires) { 2297 throw $injectorMinErr('nomod', 'Module \'{0}\' is not available! You either misspelled ' + 2298 'the module name or forgot to load it. If registering a module ensure that you ' + 2299 'specify the dependencies as the second argument.', name); 2300 } 2301 2302 /** @type {!Array.<Array.<*>>} */ 2303 var invokeQueue = []; 2304 2305 /** @type {!Array.<Function>} */ 2306 var configBlocks = []; 2307 2308 /** @type {!Array.<Function>} */ 2309 var runBlocks = []; 2310 2311 var config = invokeLater('$injector', 'invoke', 'push', configBlocks); 2312 2313 /** @type {angular.Module} */ 2314 var moduleInstance = { 2315 // Private state 2316 _invokeQueue: invokeQueue, 2317 _configBlocks: configBlocks, 2318 _runBlocks: runBlocks, 2319 2320 /** 2321 * @ngdoc method 2322 * @name angular.Module#info 2323 * @module ng 2324 * 2325 * @param {Object=} info Information about the module 2326 * @returns {Object|Module} The current info object for this module if called as a getter, 2327 * or `this` if called as a setter. 2328 * 2329 * @description 2330 * Read and write custom information about this module. 2331 * For example you could put the version of the module in here. 2332 * 2333 * ```js 2334 * angular.module('myModule', []).info({ version: '1.0.0' }); 2335 * ``` 2336 * 2337 * The version could then be read back out by accessing the module elsewhere: 2338 * 2339 * ``` 2340 * var version = angular.module('myModule').info().version; 2341 * ``` 2342 * 2343 * You can also retrieve this information during runtime via the
2344 * {@link $injector#modules `$injector.modules`} property: 2345 * 2346 * ```js 2347 * var version = $injector.modules['myModule'].info().version; 2348 * ``` 2349 */ 2350 info: function(value) { 2351 if (isDefined(value)) { 2352 if (!isObject(value)) throw ngMinErr('aobj', 'Argument \'{0}\' must be an object', 'value'); 2353 info = value; 2354 return this; 2355 } 2356 return info; 2357 }, 2358 2359 /** 2360 * @ngdoc property 2361 * @name angular.Module#requires 2362 * @module ng 2363 * 2364 * @description 2365 * Holds the list of modules which the injector will load before the current module is 2366 * loaded. 2367 */ 2368 requires: requires, 2369 2370 /** 2371 * @ngdoc property 2372 * @name angular.Module#name 2373 * @module ng 2374 * 2375 * @description 2376 * Name of the module. 2377 */ 2378 name: name, 2379 2380 2381 /** 2382 * @ngdoc method 2383 * @name angular.Module#provider 2384 * @module ng 2385 * @param {string} name service name 2386 * @param {Function} providerType Construction function for creating new instance of the 2387 * service. 2388 * @description 2389 * See {@link auto.$provide#provider $provide.provider()}. 2390 */ 2391 provider: invokeLaterAndSetModuleName('$provide', 'provider'), 2392 2393 /** 2394 * @ngdoc method 2395 * @name angular.Module#factory 2396 * @module ng 2397 * @param {string} name service name 2398 * @param {Function} providerFunction Function for creating new instance of the service. 2399 * @description 2400 * See {@link auto.$provide#factory $provide.factory()}. 2401 */ 2402 factory: invokeLaterAndSetModuleName('$provide', 'factory'), 2403 2404 /** 2405 * @ngdoc method 2406 * @name angular.Module#service 2407 * @module ng 2408 * @param {string} name service name 2409 * @param {Function} constructor A constructor function that will be instantiated. 2410 * @description 2411 * See {@link auto.$provide#service $provide.service()}. 2412 */ 2413 service: invokeLaterAndSetModuleName('$provide', 'service'), 2414 2415 /** 2416 * @ngdoc method 2417 * @name angular.Module#value 2418 * @module ng 2419 * @param {string} name service name 2420 * @param {*} object Service instance object. 2421 * @description 2422 * See {@link auto.$provide#value $provide.value()}. 2423 */ 2424 value: invokeLater('$provide', 'value'), 2425 2426 /** 2427 * @ngdoc method 2428 * @name angular.Module#constant 2429 * @module ng 2430 * @param {string} name constant name 2431 * @param {*} object Constant value. 2432 * @description 2433 * Because the constants are fixed, they get applied before other provide methods. 2434 * See {@link auto.$provide#constant $provide.constant()}. 2435 */ 2436 constant: invokeLater('$provide', 'constant', 'unshift'), 2437 2438 /** 2439 * @ngdoc method 2440 * @name angular.Module#decorator 2441 * @module ng 2442 * @param {string} name The name of the service to decorate. 2443 * @param {Function} decorFn This function will be invoked when the service needs to be 2444 * instantiated and should return the decorated service instance. 2445 * @description 2446 * See {@link auto.$provide#decorator $provide.decorator()}. 2447 */ 2448 decorator: invokeLaterAndSetModuleName('$provide', 'decorator', configBlocks), 2449 2450 /** 2451 * @ngdoc method 2452 * @name angular.Module#animation 2453 * @module ng 2454 * @param {string} name animation name 2455 * @param {Function} animationFactory Factory function for creating new instance of an 2456 * animation.
2457 * @description 2458 * 2459 * **NOTE**: animations take effect only if the **ngAnimate** module is loaded. 2460 * 2461 * 2462 * Defines an animation hook that can be later used with 2463 * {@link $animate $animate} service and directives that use this service. 2464 * 2465 * ```js 2466 * module.animation('.animation-name', function($inject1, $inject2) { 2467 * return { 2468 * eventName : function(element, done) { 2469 * //code to run the animation 2470 * //once complete, then run done() 2471 * return function cancellationFunction(element) { 2472 * //code to cancel the animation 2473 * } 2474 * } 2475 * } 2476 * }) 2477 * ``` 2478 * 2479 * See {@link ng.$animateProvider#register $animateProvider.register()} and 2480 * {@link ngAnimate ngAnimate module} for more information. 2481 */ 2482 animation: invokeLaterAndSetModuleName('$animateProvider', 'register'), 2483 2484 /** 2485 * @ngdoc method 2486 * @name angular.Module#filter 2487 * @module ng 2488 * @param {string} name Filter name - this must be a valid angular expression identifier 2489 * @param {Function} filterFactory Factory function for creating new instance of filter. 2490 * @description 2491 * See {@link ng.$filterProvider#register $filterProvider.register()}. 2492 * 2493 * <div class="alert alert-warning"> 2494 * **Note:** Filter names must be valid angular {@link expression} identifiers, such as `uppercase` or `orderBy`. 2495 * Names with special characters, such as hyphens and dots, are not allowed. If you wish to namespace 2496 * your filters, then you can use capitalization (`myappSubsectionFilterx`) or underscores 2497 * (`myapp_subsection_filterx`). 2498 * </div> 2499 */ 2500 filter: invokeLaterAndSetModuleName('$filterProvider', 'register'), 2501 2502 /** 2503 * @ngdoc method 2504 * @name angular.Module#controller 2505 * @module ng 2506 * @param {string|Object} name Controller name, or an object map of controllers where the 2507 * keys are the names and the values are the constructors. 2508 * @param {Function} constructor Controller constructor function. 2509 * @description 2510 * See {@link ng.$controllerProvider#register $controllerProvider.register()}. 2511 */ 2512 controller: invokeLaterAndSetModuleName('$controllerProvider', 'register'), 2513 2514 /** 2515 * @ngdoc method 2516 * @name angular.Module#directive 2517 * @module ng 2518 * @param {string|Object} name Directive name, or an object map of directives where the 2519 * keys are the names and the values are the factories. 2520 * @param {Function} directiveFactory Factory function for creating new instance of 2521 * directives. 2522 * @description 2523 * See {@link ng.$compileProvider#directive $compileProvider.directive()}. 2524 */ 2525 directive: invokeLaterAndSetModuleName('$compileProvider', 'directive'), 2526 2527 /** 2528 * @ngdoc method 2529 * @name angular.Module#component 2530 * @module ng 2531 * @param {string} name Name of the component in camel-case (i.e. myComp which will match as my-comp) 2532 * @param {Object} options Component definition object (a simplified 2533 * {@link ng.$compile#directive-definition-object directive definition object}) 2534 * 2535 * @description 2536 * See {@link ng.$compileProvider#component $compileProvider.component()}. 2537 */ 2538 component: invokeLaterAndSetModuleName('$compileProvider', 'component'), 2539 2540 /** 2541 * @ngdoc method 2542 * @name angular.Module#config 2543 * @module ng 2544 * @param {Function} configFn Execute this function on module load. Useful for service 2545 * configuration. 2546 * @description 2547 * Use this method to register work which needs to be performed on module loading. 2548 * For more about how to configure services, see 2549 * {@link providers#provider-recipe Provider Recipe}. 2550 */ 2551 config: config, 2552 2553 /** 2554 * @ngdoc method 2555 * @name angular.Module#run 2556 * @module ng 2557 * @param {Function} initializationFn Execute this function after injector creation. 2558 * Useful for application initialization.
vendor: 9,386 bytes, lines 2559-2895
2559 * @description 2560 * Use this method to register work which should be performed when the injector is done 2561 * loading all modules. 2562 */ 2563 run: function(block) { 2564 runBlocks.push(block); 2565 return this; 2566 } 2567 }; 2568 2569 if (configFn) { 2570 config(configFn); 2571 } 2572 2573 return moduleInstance; 2574 2575 /** 2576 * @param {string} provider 2577 * @param {string} method 2578 * @param {String=} insertMethod 2579 * @returns {angular.Module} 2580 */ 2581 function invokeLater(provider, method, insertMethod, queue) { 2582 if (!queue) queue = invokeQueue; 2583 return function() { 2584 queue[insertMethod || 'push']([provider, method, arguments]); 2585 return moduleInstance; 2586 }; 2587 } 2588 2589 /** 2590 * @param {string} provider 2591 * @param {string} method 2592 * @returns {angular.Module} 2593 */ 2594 function invokeLaterAndSetModuleName(provider, method, queue) { 2595 if (!queue) queue = invokeQueue; 2596 return function(recipeName, factoryFunction) { 2597 if (factoryFunction && isFunction(factoryFunction)) factoryFunction.$$moduleName = name; 2598 queue.push([provider, method, arguments]); 2599 return moduleInstance; 2600 }; 2601 } 2602 }); 2603 }; 2604 }); 2605 2606} 2607 2608/* global shallowCopy: true */ 2609 2610/** 2611 * Creates a shallow copy of an object, an array or a primitive. 2612 * 2613 * Assumes that there are no proto properties for objects. 2614 */ 2615function shallowCopy(src, dst) { 2616 if (isArray(src)) { 2617 dst = dst || []; 2618 2619 for (var i = 0, ii = src.length; i < ii; i++) { 2620 dst[i] = src[i]; 2621 } 2622 } else if (isObject(src)) { 2623 dst = dst || {}; 2624 2625 for (var key in src) { 2626 if (!(key.charAt(0) === '$' && key.charAt(1) === '$')) { 2627 dst[key] = src[key]; 2628 } 2629 } 2630 } 2631 2632 return dst || src; 2633} 2634 2635/* exported toDebugString */ 2636 2637function serializeObject(obj, maxDepth) { 2638 var seen = []; 2639 2640 // There is no direct way to stringify object until reaching a specific depth 2641 // and a very deep object can cause a performance issue, so we copy the object 2642 // based on this specific depth and then stringify it. 2643 if (isValidObjectMaxDepth(maxDepth)) { 2644 // This file is also included in `angular-loader`, so `copy()` might not always be available in 2645 // the closure. Therefore, it is lazily retrieved as `angular.copy()` when needed. 2646 obj = angular.copy(obj, null, maxDepth); 2647 } 2648 return JSON.stringify(obj, function(key, val) { 2649 val = toJsonReplacer(key, val); 2650 if (isObject(val)) { 2651 2652 if (seen.indexOf(val) >= 0) return '...'; 2653 2654 seen.push(val); 2655 } 2656 return val; 2657 }); 2658} 2659 2660function toDebugString(obj, maxDepth) { 2661 if (typeof obj === 'function') { 2662 return obj.toString().replace(/ \{[\s\S]*$/, ''); 2663 } else if (isUndefined(obj)) { 2664 return 'undefined'; 2665 } else if (typeof obj !== 'string') { 2666 return serializeObject(obj, maxDepth); 2667 } 2668 return obj; 2669} 2670 2671/* global angularModule: true, 2672 version: true, 2673 2674 $CompileProvider, 2675 2676 htmlAnchorDirective, 2677 inputDirective, 2678 inputDirective, 2679 formDirective, 2680 scriptDirective, 2681 selectDirective, 2682 optionDirective, 2683 ngBindDirective, 2684 ngBindHtmlDirective, 2685 ngBindTemplateDirective, 2686 ngClassDirective, 2687 ngClassEvenDirective, 2688 ngClassOddDirective, 2689 ngCloakDirective, 2690 ngControllerDirective, 2691 ngFormDirective, 2692 ngHideDirective, 2693 ngIfDirective, 2694 ngIncludeDirective, 2695 ngIncludeFillContentDirective, 2696 ngInitDirective, 2697 ngNonBindableDirective, 2698 ngPluralizeDirective, 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, 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 $IntervalProvider, 2741 $HttpProvider, 2742 $HttpParamSerializerProvider, 2743 $HttpParamSerializerJQLikeProvider, 2744 $HttpBackendProvider, 2745 $xhrFactoryProvider, 2746 $jsonpCallbacksProvider, 2747 $LocationProvider, 2748 $LogProvider, 2749 $$MapProvider, 2750 $ParseProvider, 2751 $RootScopeProvider, 2752 $QProvider, 2753 $$QProvider, 2754 $$SanitizeUriProvider, 2755 $SceProvider, 2756 $SceDelegateProvider, 2757 $SnifferProvider, 2758 $TemplateCacheProvider, 2759 $TemplateRequestProvider, 2760 $$TestabilityProvider, 2761 $TimeoutProvider, 2762 $$RAFProvider, 2763 $WindowProvider, 2764 $$jqLiteProvider, 2765 $$CookieReaderProvider 2766*/ 2767 2768 2769/** 2770 * @ngdoc object 2771 * @name angular.version 2772 * @module ng 2773 * @description 2774 * An object that contains information about the current AngularJS version. 2775 * 2776 * This object has the following properties: 2777 * 2778 * - `full` – `{string}` – Full version string, such as "0.9.18". 2779 * - `major` – `{number}` – Major version number, such as "0". 2780 * - `minor` – `{number}` – Minor version number, such as "9". 2781 * - `dot` – `{number}` – Dot version number, such as "18". 2782 * - `codeName` – `{string}` – Code name of the release, such as "jiggling-armfat". 2783 */ 2784var version = { 2785 // These placeholder strings will be replaced by grunt's `build` task. 2786 // They need to be double- or single-quoted. 2787 full: '1.6.6', 2788 major: 1, 2789 minor: 6, 2790 dot: 6, 2791 codeName: 'interdimensional-cable' 2792}; 2793 2794 2795function publishExternalAPI(angular) { 2796 extend(angular, { 2797 'errorHandlingConfig': errorHandlingConfig, 2798 'bootstrap': bootstrap, 2799 'copy': copy, 2800 'extend': extend, 2801 'merge': merge, 2802 'equals': equals, 2803 'element': jqLite, 2804 'forEach': forEach, 2805 'injector': createInjector, 2806 'noop': noop, 2807 'bind': bind, 2808 'toJson': toJson, 2809 'fromJson': fromJson, 2810 'identity': identity, 2811 'isUndefined': isUndefined, 2812 'isDefined': isDefined, 2813 'isString': isString, 2814 'isFunction': isFunction, 2815 'isObject': isObject, 2816 'isNumber': isNumber, 2817 'isElement': isElement, 2818 'isArray': isArray, 2819 'version': version, 2820 'isDate': isDate, 2821 'lowercase': lowercase, 2822 'uppercase': uppercase, 2823 'callbacks': {$$counter: 0}, 2824 'getTestability': getTestability, 2825 'reloadWithDebugInfo': reloadWithDebugInfo, 2826 '$$minErr': minErr, 2827 '$$csp': csp, 2828 '$$encodeUriSegment': encodeUriSegment, 2829 '$$encodeUriQuery': encodeUriQuery, 2830 '$$stringify': stringify 2831 }); 2832 2833 angularModule = setupModuleLoader(window); 2834 2835 angularModule('ng', ['ngLocale'], ['$provide', 2836 function ngModule($provide) { 2837 // $$sanitizeUriProvider needs to be before $compileProvider as it is used by it. 2838 $provide.provider({ 2839 $$sanitizeUri: $$SanitizeUriProvider 2840 }); 2841 $provide.provider('$compile', $CompileProvider). 2842 directive({ 2843 a: htmlAnchorDirective, 2844 input: inputDirective, 2845 textarea: inputDirective, 2846 form: formDirective, 2847 script: scriptDirective, 2848 select: selectDirective, 2849 option: optionDirective, 2850 ngBind: ngBindDirective, 2851 ngBindHtml: ngBindHtmlDirective, 2852 ngBindTemplate: ngBindTemplateDirective, 2853 ngClass: ngClassDirective, 2854 ngClassEven: ngClassEvenDirective, 2855 ngClassOdd: ngClassOddDirective, 2856 ngCloak: ngCloakDirective, 2857 ngController: ngControllerDirective, 2858 ngForm: ngFormDirective, 2859 ngHide: ngHideDirective, 2860 ngIf: ngIfDirective, 2861 ngInclude: ngIncludeDirective, 2862 ngInit: ngInitDirective, 2863 ngNonBindable: ngNonBindableDirective, 2864 ngPluralize: ngPluralizeDirective, 2865 ngRepeat: ngRepeatDirective, 2866 ngShow: ngShowDirective, 2867 ngStyle: ngStyleDirective, 2868 ngSwitch: ngSwitchDirective, 2869 ngSwitchWhen: ngSwitchWhenDirective, 2870 ngSwitchDefault: ngSwitchDefaultDirective, 2871 ngOptions: ngOptionsDirective, 2872 ngTransclude: ngTranscludeDirective, 2873 ngModel: ngModelDirective, 2874 ngList: ngListDirective, 2875 ngChange: ngChangeDirective, 2876 pattern: patternDirective, 2877 ngPattern: patternDirective, 2878 required: requiredDirective, 2879 ngRequired: requiredDirective, 2880 minlength: minlengthDirective, 2881 ngMinlength: minlengthDirective, 2882 maxlength: maxlengthDirective, 2883 ngMaxlength: maxlengthDirective, 2884 ngValue: ngValueDirective, 2885 ngModelOptions: ngModelOptionsDirective 2886 }). 2887 directive({ 2888 ngInclude: ngIncludeFillContentDirective 2889 }). 2890 directive(ngAttributeAliasDirectives). 2891 directive(ngEventDirectives); 2892 $provide.provider({ 2893 $anchorScroll: $AnchorScrollProvider, 2894 $animate: $AnimateProvider, 2895 $animateCss: $CoreAnimateCssProvider,
2896 $$animateJs: $$CoreAnimateJsProvider, 2897 $$animateQueue: $$CoreAnimateQueueProvider, 2898 $$AnimateRunner: $$AnimateRunnerFactoryProvider, 2899 $$animateAsyncRun: $$AnimateAsyncRunFactoryProvider, 2900 $browser: $BrowserProvider, 2901 $cacheFactory: $CacheFactoryProvider, 2902 $controller: $ControllerProvider, 2903 $document: $DocumentProvider, 2904 $$isDocumentHidden: $$IsDocumentHiddenProvider, 2905 $exceptionHandler: $ExceptionHandlerProvider, 2906 $filter: $FilterProvider, 2907 $$forceReflow: $$ForceReflowProvider, 2908 $interpolate: $InterpolateProvider, 2909 $interval: $IntervalProvider, 2910 $http: $HttpProvider, 2911 $httpParamSerializer: $HttpParamSerializerProvider, 2912 $httpParamSerializerJQLike: $HttpParamSerializerJQLikeProvider, 2913 $httpBackend: $HttpBackendProvider, 2914 $xhrFactory: $xhrFactoryProvider, 2915 $jsonpCallbacks: $jsonpCallbacksProvider, 2916 $location: $LocationProvider, 2917 $log: $LogProvider, 2918 $parse: $ParseProvider, 2919 $rootScope: $RootScopeProvider, 2920 $q: $QProvider, 2921 $$q: $$QProvider, 2922 $sce: $SceProvider, 2923 $sceDelegate: $SceDelegateProvider, 2924 $sniffer: $SnifferProvider, 2925 $templateCache: $TemplateCacheProvider, 2926 $templateRequest: $TemplateRequestProvider, 2927 $$testability: $$TestabilityProvider, 2928 $timeout: $TimeoutProvider, 2929 $window: $WindowProvider, 2930 $$rAF: $$RAFProvider, 2931 $$jqLite: $$jqLiteProvider, 2932 $$Map: $$MapProvider, 2933 $$cookieReader: $$CookieReaderProvider 2934 }); 2935 } 2936 ]) 2937 .info({ angularVersion: '1.6.6' }); 2938} 2939 2940/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * 2941 * Any commits to this file should be reviewed with security in mind. * 2942 * Changes to this file can potentially create security vulnerabilities. * 2943 * An approval from 2 Core members with history of modifying * 2944 * this file is required. * 2945 * * 2946 * Does the change somehow allow for arbitrary javascript to be executed? * 2947 * Or allows for someone to change the prototype of built-in objects? * 2948 * Or gives undesired access to variables likes document or window? * 2949 * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ 2950 2951/* global 2952 JQLitePrototype: true, 2953 BOOLEAN_ATTR: true, 2954 ALIASED_ATTR: true 2955*/ 2956 2957////////////////////////////////// 2958//JQLite 2959////////////////////////////////// 2960 2961/** 2962 * @ngdoc function 2963 * @name angular.element 2964 * @module ng 2965 * @kind function 2966 * 2967 * @description 2968 * Wraps a raw DOM element or HTML string as a [jQuery](http://jquery.com) element. 2969 * 2970 * If jQuery is available, `angular.element` is an alias for the 2971 * [jQuery](http://api.jquery.com/jQuery/) function. If jQuery is not available, `angular.element` 2972 * delegates to Angular's built-in subset of jQuery, called "jQuery lite" or **jqLite**. 2973 * 2974 * jqLite is a tiny, API-compatible subset of jQuery that allows 2975 * Angular to manipulate the DOM in a cross-browser compatible way. jqLite implements only the most 2976 * commonly needed functionality with the goal of having a very small footprint. 2977 * 2978 * To use `jQuery`, simply ensure it is loaded before the `angular.js` file. You can also use the 2979 * {@link ngJq `ngJq`} directive to specify that jqlite should be used over jQuery, or to use a 2980 * specific version of jQuery if multiple versions exist on the page. 2981 * 2982 * <div class="alert alert-info">**Note:** All element references in Angular are always wrapped with jQuery or 2983 * jqLite (such as the element argument in a directive's compile / link function). They are never raw DOM references.</div> 2984 * 2985 * <div class="alert alert-warning">**Note:** Keep in mind that this function will not find elements 2986 * by tag name / CSS selector. For lookups by tag name, try instead `angular.element(document).find(...)` 2987 * or `$document.find()`, or use the standard DOM APIs, e.g. `document.querySelectorAll()`.</div> 2988 * 2989 * ## Angular's jqLite 2990 * jqLite provides only the following jQuery methods: 2991 * 2992 * - [`addClass()`](http://api.jquery.com/addClass/) - Does not support a function as first argument 2993 * - [`after()`](http://api.jquery.com/after/) 2994 * - [`append()`](http://api.jquery.com/append/) 2995 * - [`attr()`](http://api.jquery.com/attr/) - Does not support functions as parameters 2996 * - [`bind()`](http://api.jquery.com/bind/) (_deprecated_, use [`on()`](http://api.jquery.com/on/)) - Does not support namespaces, selectors or eventData 2997 * - [`children()`](http://api.jquery.com/children/) - Does not support selectors 2998 * - [`clone()`](http://api.jquery.com/clone/) 2999 * - [`contents()`](http://api.jquery.com/contents/) 3000 * - [`css()`](http://api.jquery.com/css/) - Only retrieves inline-styles, does not call `getComputedStyle()`.
3001 * As a setter, does not convert numbers to strings or append 'px', and also does not have automatic property prefixing. 3002 * - [`data()`](http://api.jquery.com/data/) 3003 * - [`detach()`](http://api.jquery.com/detach/) 3004 * - [`empty()`](http://api.jquery.com/empty/) 3005 * - [`eq()`](http://api.jquery.com/eq/) 3006 * - [`find()`](http://api.jquery.com/find/) - Limited to lookups by tag name 3007 * - [`hasClass()`](http://api.jquery.com/hasClass/) 3008 * - [`html()`](http://api.jquery.com/html/) 3009 * - [`next()`](http://api.jquery.com/next/) - Does not support selectors 3010 * - [`on()`](http://api.jquery.com/on/) - Does not support namespaces, selectors or eventData 3011 * - [`off()`](http://api.jquery.com/off/) - Does not support namespaces, selectors or event object as parameter 3012 * - [`one()`](http://api.jquery.com/one/) - Does not support namespaces or selectors 3013 * - [`parent()`](http://api.jquery.com/parent/) - Does not support selectors 3014 * - [`prepend()`](http://api.jquery.com/prepend/) 3015 * - [`prop()`](http://api.jquery.com/prop/) 3016 * - [`ready()`](http://api.jquery.com/ready/) (_deprecated_, use `angular.element(callback)` instead of `angular.element(document).ready(callback)`) 3017 * - [`remove()`](http://api.jquery.com/remove/) 3018 * - [`removeAttr()`](http://api.jquery.com/removeAttr/) - Does not support multiple attributes 3019 * - [`removeClass()`](http://api.jquery.com/removeClass/) - Does not support a function as first argument 3020 * - [`removeData()`](http://api.jquery.com/removeData/) 3021 * - [`replaceWith()`](http://api.jquery.com/replaceWith/) 3022 * - [`text()`](http://api.jquery.com/text/) 3023 * - [`toggleClass()`](http://api.jquery.com/toggleClass/) - Does not support a function as first argument 3024 * - [`triggerHandler()`](http://api.jquery.com/triggerHandler/) - Passes a dummy event object to handlers 3025 * - [`unbind()`](http://api.jquery.com/unbind/) (_deprecated_, use [`off()`](http://api.jquery.com/off/)) - Does not support namespaces or event object as parameter 3026 * - [`val()`](http://api.jquery.com/val/) 3027 * - [`wrap()`](http://api.jquery.com/wrap/) 3028 * 3029 * ## jQuery/jqLite Extras 3030 * Angular also provides the following additional methods and events to both jQuery and jqLite: 3031 * 3032 * ### Events 3033 * - `$destroy` - AngularJS intercepts all jqLite/jQuery's DOM destruction apis and fires this event 3034 * on all DOM nodes being removed. This can be used to clean up any 3rd party bindings to the DOM 3035 * element before it is removed. 3036 * 3037 * ### Methods 3038 * - `controller(name)` - retrieves the controller of the current element or its parent. By default 3039 * retrieves controller associated with the `ngController` directive. If `name` is provided as 3040 * camelCase directive name, then the controller for this directive will be retrieved (e.g. 3041 * `'ngModel'`). 3042 * - `injector()` - retrieves the injector of the current element or its parent. 3043 * - `scope()` - retrieves the {@link ng.$rootScope.Scope scope} of the current 3044 * element or its parent. Requires {@link guide/production#disabling-debug-data Debug Data} to 3045 * be enabled. 3046 * - `isolateScope()` - retrieves an isolate {@link ng.$rootScope.Scope scope} if one is attached directly to the 3047 * current element. This getter should be used only on elements that contain a directive which starts a new isolate 3048 * scope. Calling `scope()` on this element always returns the original non-isolate scope. 3049 * Requires {@link guide/production#disabling-debug-data Debug Data} to be enabled. 3050 * - `inheritedData()` - same as `data()`, but walks up the DOM until a value is found or the top 3051 * parent element is reached. 3052 * 3053 * @knownIssue You cannot spy on `angular.element` if you are using Jasmine version 1.x. See 3054 * https://github.com/angular/angular.js/issues/14251 for more information. 3055 * 3056 * @param {string|DOMElement} element HTML string or DOMElement to be wrapped into jQuery. 3057 * @returns {Object} jQuery object. 3058 */ 3059 3060JQLite.expando = 'ng339'; 3061 3062var jqCache = JQLite.cache = {}, 3063 jqId = 1; 3064 3065/* 3066 * !!! This is an undocumented "private" function !!! 3067 */ 3068JQLite._data = function(node) { 3069 //jQuery always returns an object on cache miss 3070 return this.cache[node[this.expando]] || {}; 3071}; 3072 3073function jqNextId() { return ++jqId; } 3074 3075 3076var DASH_LOWERCASE_REGEXP = /-([a-z])/g; 3077var MS_HACK_REGEXP = /^-ms-/; 3078var MOUSE_EVENT_MAP = { mouseleave: 'mouseout', mouseenter: 'mouseover' }; 3079var jqLiteMinErr = minErr('jqLite'); 3080 3081/** 3082 * Converts kebab-case to camelCase. 3083 * There is also a special case for the ms prefix starting with a lowercase letter. 3084 * @param name Name to normalize 3085 */ 3086function cssKebabToCamel(name) { 3087 return kebabToCamel(name.replace(MS_HACK_REGEXP, 'ms-')); 3088} 3089 3090function fnCamelCaseReplace(all, letter) { 3091 return letter.toUpperCase(); 3092} 3093 3094/** 3095 * Converts kebab-case to camelCase. 3096 * @param name Name to normalize 3097 */ 3098function kebabToCamel(name) { 3099 return name 3100 .replace(DASH_LOWERCASE_REGEXP, fnCamelCaseReplace); 3101} 3102 3103var SINGLE_TAG_REGEXP = /^<([\w-]+)\s*\/?>(?:<\/\1>|)$/;
vendor: 12,418 bytes, lines 3104-3546
3104var HTML_REGEXP = /<|&#?\w+;/; 3105var TAG_NAME_REGEXP = /<([\w:-]+)/; 3106var XHTML_TAG_REGEXP = /<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:-]+)[^>]*)\/>/gi; 3107 3108var wrapMap = { 3109 'option': [1, '<select multiple="multiple">', '</select>'], 3110 3111 'thead': [1, '<table>', '</table>'], 3112 'col': [2, '<table><colgroup>', '</colgroup></table>'], 3113 'tr': [2, '<table><tbody>', '</tbody></table>'], 3114 'td': [3, '<table><tbody><tr>', '</tr></tbody></table>'], 3115 '_default': [0, '', ''] 3116}; 3117 3118wrapMap.optgroup = wrapMap.option; 3119wrapMap.tbody = wrapMap.tfoot = wrapMap.colgroup = wrapMap.caption = wrapMap.thead; 3120wrapMap.th = wrapMap.td; 3121 3122 3123function jqLiteIsTextNode(html) { 3124 return !HTML_REGEXP.test(html); 3125} 3126 3127function jqLiteAcceptsData(node) { 3128 // The window object can accept data but has no nodeType 3129 // Otherwise we are only interested in elements (1) and documents (9) 3130 var nodeType = node.nodeType; 3131 return nodeType === NODE_TYPE_ELEMENT || !nodeType || nodeType === NODE_TYPE_DOCUMENT; 3132} 3133 3134function jqLiteHasData(node) { 3135 for (var key in jqCache[node.ng339]) { 3136 return true; 3137 } 3138 return false; 3139} 3140 3141function jqLiteBuildFragment(html, context) { 3142 var tmp, tag, wrap, 3143 fragment = context.createDocumentFragment(), 3144 nodes = [], i; 3145 3146 if (jqLiteIsTextNode(html)) { 3147 // Convert non-html into a text node 3148 nodes.push(context.createTextNode(html)); 3149 } else { 3150 // Convert html into DOM nodes 3151 tmp = fragment.appendChild(context.createElement('div')); 3152 tag = (TAG_NAME_REGEXP.exec(html) || ['', ''])[1].toLowerCase(); 3153 wrap = wrapMap[tag] || wrapMap._default; 3154 tmp.innerHTML = wrap[1] + html.replace(XHTML_TAG_REGEXP, '<$1></$2>') + wrap[2]; 3155 3156 // Descend through wrappers to the right content 3157 i = wrap[0]; 3158 while (i--) { 3159 tmp = tmp.lastChild; 3160 } 3161 3162 nodes = concat(nodes, tmp.childNodes); 3163 3164 tmp = fragment.firstChild; 3165 tmp.textContent = ''; 3166 } 3167 3168 // Remove wrapper from fragment 3169 fragment.textContent = ''; 3170 fragment.innerHTML = ''; // Clear inner HTML 3171 forEach(nodes, function(node) { 3172 fragment.appendChild(node); 3173 }); 3174 3175 return fragment; 3176} 3177 3178function jqLiteParseHTML(html, context) { 3179 context = context || window.document; 3180 var parsed; 3181 3182 if ((parsed = SINGLE_TAG_REGEXP.exec(html))) { 3183 return [context.createElement(parsed[1])]; 3184 } 3185 3186 if ((parsed = jqLiteBuildFragment(html, context))) { 3187 return parsed.childNodes; 3188 } 3189 3190 return []; 3191} 3192 3193function jqLiteWrapNode(node, wrapper) { 3194 var parent = node.parentNode; 3195 3196 if (parent) { 3197 parent.replaceChild(wrapper, node); 3198 } 3199 3200 wrapper.appendChild(node); 3201} 3202 3203 3204// IE9-11 has no method "contains" in SVG element and in Node.prototype. Bug #10259. 3205var jqLiteContains = window.Node.prototype.contains || /** @this */ function(arg) { 3206 // eslint-disable-next-line no-bitwise 3207 return !!(this.compareDocumentPosition(arg) & 16); 3208}; 3209 3210///////////////////////////////////////////// 3211function JQLite(element) { 3212 if (element instanceof JQLite) { 3213 return element; 3214 } 3215 3216 var argIsString; 3217 3218 if (isString(element)) { 3219 element = trim(element); 3220 argIsString = true; 3221 } 3222 if (!(this instanceof JQLite)) { 3223 if (argIsString && element.charAt(0) !== '<') { 3224 throw jqLiteMinErr('nosel', 'Looking up elements via selectors is not supported by jqLite! See: http://docs.angularjs.org/api/angular.element'); 3225 } 3226 return new JQLite(element); 3227 } 3228 3229 if (argIsString) { 3230 jqLiteAddNodes(this, jqLiteParseHTML(element)); 3231 } else if (isFunction(element)) { 3232 jqLiteReady(element); 3233 } else { 3234 jqLiteAddNodes(this, element); 3235 } 3236} 3237 3238function jqLiteClone(element) { 3239 return element.cloneNode(true); 3240} 3241 3242function jqLiteDealoc(element, onlyDescendants) { 3243 if (!onlyDescendants && jqLiteAcceptsData(element)) jqLite.cleanData([element]); 3244 3245 if (element.querySelectorAll) { 3246 jqLite.cleanData(element.querySelectorAll('*')); 3247 } 3248} 3249 3250function jqLiteOff(element, type, fn, unsupported) { 3251 if (isDefined(unsupported)) throw jqLiteMinErr('offargs', 'jqLite#off() does not support the `selector` argument'); 3252 3253 var expandoStore = jqLiteExpandoStore(element); 3254 var events = expandoStore && expandoStore.events; 3255 var handle = expandoStore && expandoStore.handle; 3256 3257 if (!handle) return; //no listeners registered 3258 3259 if (!type) { 3260 for (type in events) { 3261 if (type !== '$destroy') { 3262 element.removeEventListener(type, handle); 3263 } 3264 delete events[type]; 3265 } 3266 } else { 3267 3268 var removeHandler = function(type) { 3269 var listenerFns = events[type]; 3270 if (isDefined(fn)) { 3271 arrayRemove(listenerFns || [], fn); 3272 } 3273 if (!(isDefined(fn) && listenerFns && listenerFns.length > 0)) { 3274 element.removeEventListener(type, handle); 3275 delete events[type]; 3276 } 3277 }; 3278 3279 forEach(type.split(' '), function(type) { 3280 removeHandler(type); 3281 if (MOUSE_EVENT_MAP[type]) { 3282 removeHandler(MOUSE_EVENT_MAP[type]); 3283 } 3284 }); 3285 } 3286} 3287 3288function jqLiteRemoveData(element, name) { 3289 var expandoId = element.ng339; 3290 var expandoStore = expandoId && jqCache[expandoId]; 3291 3292 if (expandoStore) { 3293 if (name) { 3294 delete expandoStore.data[name]; 3295 return; 3296 } 3297 3298 if (expandoStore.handle) { 3299 if (expandoStore.events.$destroy) { 3300 expandoStore.handle({}, '$destroy'); 3301 } 3302 jqLiteOff(element); 3303 } 3304 delete jqCache[expandoId]; 3305 element.ng339 = undefined; // don't delete DOM expandos. IE and Chrome don't like it 3306 } 3307} 3308 3309 3310function jqLiteExpandoStore(element, createIfNecessary) { 3311 var expandoId = element.ng339, 3312 expandoStore = expandoId && jqCache[expandoId]; 3313 3314 if (createIfNecessary && !expandoStore) { 3315 element.ng339 = expandoId = jqNextId(); 3316 expandoStore = jqCache[expandoId] = {events: {}, data: {}, handle: undefined}; 3317 } 3318 3319 return expandoStore; 3320} 3321 3322 3323function jqLiteData(element, key, value) { 3324 if (jqLiteAcceptsData(element)) { 3325 var prop; 3326 3327 var isSimpleSetter = isDefined(value); 3328 var isSimpleGetter = !isSimpleSetter && key && !isObject(key); 3329 var massGetter = !key; 3330 var expandoStore = jqLiteExpandoStore(element, !isSimpleGetter); 3331 var data = expandoStore && expandoStore.data; 3332 3333 if (isSimpleSetter) { // data('key', value) 3334 data[kebabToCamel(key)] = value; 3335 } else { 3336 if (massGetter) { // data() 3337 return data; 3338 } else { 3339 if (isSimpleGetter) { // data('key') 3340 // don't force creation of expandoStore if it doesn't exist yet 3341 return data && data[kebabToCamel(key)]; 3342 } else { // mass-setter: data({key1: val1, key2: val2}) 3343 for (prop in key) { 3344 data[kebabToCamel(prop)] = key[prop]; 3345 } 3346 } 3347 } 3348 } 3349 } 3350} 3351 3352function jqLiteHasClass(element, selector) { 3353 if (!element.getAttribute) return false; 3354 return ((' ' + (element.getAttribute('class') || '') + ' ').replace(/[\n\t]/g, ' '). 3355 indexOf(' ' + selector + ' ') > -1); 3356} 3357 3358function jqLiteRemoveClass(element, cssClasses) { 3359 if (cssClasses && element.setAttribute) { 3360 forEach(cssClasses.split(' '), function(cssClass) { 3361 element.setAttribute('class', trim( 3362 (' ' + (element.getAttribute('class') || '') + ' ') 3363 .replace(/[\n\t]/g, ' ') 3364 .replace(' ' + trim(cssClass) + ' ', ' ')) 3365 ); 3366 }); 3367 } 3368} 3369 3370function jqLiteAddClass(element, cssClasses) { 3371 if (cssClasses && element.setAttribute) { 3372 var existingClasses = (' ' + (element.getAttribute('class') || '') + ' ') 3373 .replace(/[\n\t]/g, ' '); 3374 3375 forEach(cssClasses.split(' '), function(cssClass) { 3376 cssClass = trim(cssClass); 3377 if (existingClasses.indexOf(' ' + cssClass + ' ') === -1) { 3378 existingClasses += cssClass + ' '; 3379 } 3380 }); 3381 3382 element.setAttribute('class', trim(existingClasses)); 3383 } 3384} 3385 3386 3387function jqLiteAddNodes(root, elements) { 3388 // THIS CODE IS VERY HOT. Don't make changes without benchmarking. 3389 3390 if (elements) { 3391 3392 // if a Node (the most common case) 3393 if (elements.nodeType) { 3394 root[root.length++] = elements; 3395 } else { 3396 var length = elements.length; 3397 3398 // if an Array or NodeList and not a Window 3399 if (typeof length === 'number' && elements.window !== elements) { 3400 if (length) { 3401 for (var i = 0; i < length; i++) { 3402 root[root.length++] = elements[i]; 3403 } 3404 } 3405 } else { 3406 root[root.length++] = elements; 3407 } 3408 } 3409 } 3410} 3411 3412 3413function jqLiteController(element, name) { 3414 return jqLiteInheritedData(element, '$' + (name || 'ngController') + 'Controller'); 3415} 3416 3417function jqLiteInheritedData(element, name, value) { 3418 // if element is the document object work with the html element instead 3419 // this makes $(document).scope() possible 3420 if (element.nodeType === NODE_TYPE_DOCUMENT) { 3421 element = element.documentElement; 3422 } 3423 var names = isArray(name) ? name : [name]; 3424 3425 while (element) { 3426 for (var i = 0, ii = names.length; i < ii; i++) { 3427 if (isDefined(value = jqLite.data(element, names[i]))) return value; 3428 } 3429 3430 // If dealing with a document fragment node with a host element, and no parent, use the host 3431 // element as the parent. This enables directives within a Shadow DOM or polyfilled Shadow DOM 3432 // to lookup parent controllers. 3433 element = element.parentNode || (element.nodeType === NODE_TYPE_DOCUMENT_FRAGMENT && element.host); 3434 } 3435} 3436 3437function jqLiteEmpty(element) { 3438 jqLiteDealoc(element, true); 3439 while (element.firstChild) { 3440 element.removeChild(element.firstChild); 3441 } 3442} 3443 3444function jqLiteRemove(element, keepData) { 3445 if (!keepData) jqLiteDealoc(element); 3446 var parent = element.parentNode; 3447 if (parent) parent.removeChild(element); 3448} 3449 3450 3451function jqLiteDocumentLoaded(action, win) { 3452 win = win || window; 3453 if (win.document.readyState === 'complete') { 3454 // Force the action to be run async for consistent behavior 3455 // from the action's point of view 3456 // i.e. it will definitely not be in a $apply 3457 win.setTimeout(action); 3458 } else { 3459 // No need to unbind this handler as load is only ever called once 3460 jqLite(win).on('load', action); 3461 } 3462} 3463 3464function jqLiteReady(fn) { 3465 function trigger() { 3466 window.document.removeEventListener('DOMContentLoaded', trigger); 3467 window.removeEventListener('load', trigger); 3468 fn(); 3469 } 3470 3471 // check if document is already loaded 3472 if (window.document.readyState === 'complete') { 3473 window.setTimeout(fn); 3474 } else { 3475 // We can not use jqLite since we are not done loading and jQuery could be loaded later. 3476 3477 // Works for modern browsers and IE9 3478 window.document.addEventListener('DOMContentLoaded', trigger); 3479 3480 // Fallback to window.onload for others 3481 window.addEventListener('load', trigger); 3482 } 3483} 3484 3485////////////////////////////////////////// 3486// Functions which are declared directly. 3487////////////////////////////////////////// 3488var JQLitePrototype = JQLite.prototype = { 3489 ready: jqLiteReady, 3490 toString: function() { 3491 var value = []; 3492 forEach(this, function(e) { value.push('' + e);}); 3493 return '[' + value.join(', ') + ']'; 3494 }, 3495 3496 eq: function(index) { 3497 return (index >= 0) ? jqLite(this[index]) : jqLite(this[this.length + index]); 3498 }, 3499 3500 length: 0, 3501 push: push, 3502 sort: [].sort, 3503 splice: [].splice 3504}; 3505 3506////////////////////////////////////////// 3507// Functions iterating getter/setters. 3508// these functions return self on setter and 3509// value on get. 3510////////////////////////////////////////// 3511var BOOLEAN_ATTR = {}; 3512forEach('multiple,selected,checked,disabled,readOnly,required,open'.split(','), function(value) { 3513 BOOLEAN_ATTR[lowercase(value)] = value; 3514}); 3515var BOOLEAN_ELEMENTS = {}; 3516forEach('input,select,option,textarea,button,form,details'.split(','), function(value) { 3517 BOOLEAN_ELEMENTS[value] = true; 3518}); 3519var ALIASED_ATTR = { 3520 'ngMinlength': 'minlength', 3521 'ngMaxlength': 'maxlength', 3522 'ngMin': 'min', 3523 'ngMax': 'max', 3524 'ngPattern': 'pattern', 3525 'ngStep': 'step' 3526}; 3527 3528function getBooleanAttrName(element, name) { 3529 // check dom last since we will most likely fail on name 3530 var booleanAttr = BOOLEAN_ATTR[name.toLowerCase()]; 3531 3532 // booleanAttr is here twice to minimize DOM access 3533 return booleanAttr && BOOLEAN_ELEMENTS[nodeName_(element)] && booleanAttr; 3534} 3535 3536function getAliasedAttrName(name) { 3537 return ALIASED_ATTR[name]; 3538} 3539 3540forEach({ 3541 data: jqLiteData, 3542 removeData: jqLiteRemoveData, 3543 hasData: jqLiteHasData, 3544 cleanData: function jqLiteCleanData(nodes) { 3545 for (var i = 0, ii = nodes.length; i < ii; i++) { 3546 jqLiteRemoveData
vendor: 15,540 bytes, lines 3546-4089
3546(nodes[i]); 3547 } 3548 } 3549}, function(fn, name) { 3550 JQLite[name] = fn; 3551}); 3552 3553forEach({ 3554 data: jqLiteData, 3555 inheritedData: jqLiteInheritedData, 3556 3557 scope: function(element) { 3558 // Can't use jqLiteData here directly so we stay compatible with jQuery! 3559 return jqLite.data(element, '$scope') || jqLiteInheritedData(element.parentNode || element, ['$isolateScope', '$scope']); 3560 }, 3561 3562 isolateScope: function(element) { 3563 // Can't use jqLiteData here directly so we stay compatible with jQuery! 3564 return jqLite.data(element, '$isolateScope') || jqLite.data(element, '$isolateScopeNoTemplate'); 3565 }, 3566 3567 controller: jqLiteController, 3568 3569 injector: function(element) { 3570 return jqLiteInheritedData(element, '$injector'); 3571 }, 3572 3573 removeAttr: function(element, name) { 3574 element.removeAttribute(name); 3575 }, 3576 3577 hasClass: jqLiteHasClass, 3578 3579 css: function(element, name, value) { 3580 name = cssKebabToCamel(name); 3581 3582 if (isDefined(value)) { 3583 element.style[name] = value; 3584 } else { 3585 return element.style[name]; 3586 } 3587 }, 3588 3589 attr: function(element, name, value) { 3590 var ret; 3591 var nodeType = element.nodeType; 3592 if (nodeType === NODE_TYPE_TEXT || nodeType === NODE_TYPE_ATTRIBUTE || nodeType === NODE_TYPE_COMMENT || 3593 !element.getAttribute) { 3594 return; 3595 } 3596 3597 var lowercasedName = lowercase(name); 3598 var isBooleanAttr = BOOLEAN_ATTR[lowercasedName]; 3599 3600 if (isDefined(value)) { 3601 // setter 3602 3603 if (value === null || (value === false && isBooleanAttr)) { 3604 element.removeAttribute(name); 3605 } else { 3606 element.setAttribute(name, isBooleanAttr ? lowercasedName : value); 3607 } 3608 } else { 3609 // getter 3610 3611 ret = element.getAttribute(name); 3612 3613 if (isBooleanAttr && ret !== null) { 3614 ret = lowercasedName; 3615 } 3616 // Normalize non-existing attributes to undefined (as jQuery). 3617 return ret === null ? undefined : ret; 3618 } 3619 }, 3620 3621 prop: function(element, name, value) { 3622 if (isDefined(value)) { 3623 element[name] = value; 3624 } else { 3625 return element[name]; 3626 } 3627 }, 3628 3629 text: (function() { 3630 getText.$dv = ''; 3631 return getText; 3632 3633 function getText(element, value) { 3634 if (isUndefined(value)) { 3635 var nodeType = element.nodeType; 3636 return (nodeType === NODE_TYPE_ELEMENT || nodeType === NODE_TYPE_TEXT) ? element.textContent : ''; 3637 } 3638 element.textContent = value; 3639 } 3640 })(), 3641 3642 val: function(element, value) { 3643 if (isUndefined(value)) { 3644 if (element.multiple && nodeName_(element) === 'select') { 3645 var result = []; 3646 forEach(element.options, function(option) { 3647 if (option.selected) { 3648 result.push(option.value || option.text); 3649 } 3650 }); 3651 return result; 3652 } 3653 return element.value; 3654 } 3655 element.value = value; 3656 }, 3657 3658 html: function(element, value) { 3659 if (isUndefined(value)) { 3660 return element.innerHTML; 3661 } 3662 jqLiteDealoc(element, true); 3663 element.innerHTML = value; 3664 }, 3665 3666 empty: jqLiteEmpty 3667}, function(fn, name) { 3668 /** 3669 * Properties: writes return selection, reads return first value 3670 */ 3671 JQLite.prototype[name] = function(arg1, arg2) { 3672 var i, key; 3673 var nodeCount = this.length; 3674 3675 // jqLiteHasClass has only two arguments, but is a getter-only fn, so we need to special-case it 3676 // in a way that survives minification. 3677 // jqLiteEmpty takes no arguments but is a setter. 3678 if (fn !== jqLiteEmpty && 3679 (isUndefined((fn.length === 2 && (fn !== jqLiteHasClass && fn !== jqLiteController)) ? arg1 : arg2))) { 3680 if (isObject(arg1)) { 3681 3682 // we are a write, but the object properties are the key/values 3683 for (i = 0; i < nodeCount; i++) { 3684 if (fn === jqLiteData) { 3685 // data() takes the whole object in jQuery 3686 fn(this[i], arg1); 3687 } else { 3688 for (key in arg1) { 3689 fn(this[i], key, arg1[key]); 3690 } 3691 } 3692 } 3693 // return self for chaining 3694 return this; 3695 } else { 3696 // we are a read, so read the first child. 3697 // TODO: do we still need this? 3698 var value = fn.$dv; 3699 // Only if we have $dv do we iterate over all, otherwise it is just the first element. 3700 var jj = (isUndefined(value)) ? Math.min(nodeCount, 1) : nodeCount; 3701 for (var j = 0; j < jj; j++) { 3702 var nodeValue = fn(this[j], arg1, arg2); 3703 value = value ? value + nodeValue : nodeValue; 3704 } 3705 return value; 3706 } 3707 } else { 3708 // we are a write, so apply to all children 3709 for (i = 0; i < nodeCount; i++) { 3710 fn(this[i], arg1, arg2); 3711 } 3712 // return self for chaining 3713 return this; 3714 } 3715 }; 3716}); 3717 3718function createEventHandler(element, events) { 3719 var eventHandler = function(event, type) { 3720 // jQuery specific api 3721 event.isDefaultPrevented = function() { 3722 return event.defaultPrevented; 3723 }; 3724 3725 var eventFns = events[type || event.type]; 3726 var eventFnsLength = eventFns ? eventFns.length : 0; 3727 3728 if (!eventFnsLength) return; 3729 3730 if (isUndefined(event.immediatePropagationStopped)) { 3731 var originalStopImmediatePropagation = event.stopImmediatePropagation; 3732 event.stopImmediatePropagation = function() { 3733 event.immediatePropagationStopped = true; 3734 3735 if (event.stopPropagation) { 3736 event.stopPropagation(); 3737 } 3738 3739 if (originalStopImmediatePropagation) { 3740 originalStopImmediatePropagation.call(event); 3741 } 3742 }; 3743 } 3744 3745 event.isImmediatePropagationStopped = function() { 3746 return event.immediatePropagationStopped === true; 3747 }; 3748 3749 // Some events have special handlers that wrap the real handler 3750 var handlerWrapper = eventFns.specialHandlerWrapper || defaultHandlerWrapper; 3751 3752 // Copy event handlers in case event handlers array is modified during execution. 3753 if ((eventFnsLength > 1)) { 3754 eventFns = shallowCopy(eventFns); 3755 } 3756 3757 for (var i = 0; i < eventFnsLength; i++) { 3758 if (!event.isImmediatePropagationStopped()) { 3759 handlerWrapper(element, event, eventFns[i]); 3760 } 3761 } 3762 }; 3763 3764 // TODO: this is a hack for angularMocks/clearDataCache that makes it possible to deregister all 3765 // events on `element` 3766 eventHandler.elem = element; 3767 return eventHandler; 3768} 3769 3770function defaultHandlerWrapper(element, event, handler) { 3771 handler.call(element, event); 3772} 3773 3774function specialMouseHandlerWrapper(target, event, handler) { 3775 // Refer to jQuery's implementation of mouseenter & mouseleave 3776 // Read about mouseenter and mouseleave: 3777 // http://www.quirksmode.org/js/events_mouse.html#link8 3778 var related = event.relatedTarget; 3779 // For mousenter/leave call the handler if related is outside the target. 3780 // NB: No relatedTarget if the mouse left/entered the browser window 3781 if (!related || (related !== target && !jqLiteContains.call(target, related))) { 3782 handler.call(target, event); 3783 } 3784} 3785 3786////////////////////////////////////////// 3787// Functions iterating traversal. 3788// These functions chain results into a single 3789// selector. 3790////////////////////////////////////////// 3791forEach({ 3792 removeData: jqLiteRemoveData, 3793 3794 on: function jqLiteOn(element, type, fn, unsupported) { 3795 if (isDefined(unsupported)) throw jqLiteMinErr('onargs', 'jqLite#on() does not support the `selector` or `eventData` parameters'); 3796 3797 // Do not add event handlers to non-elements because they will not be cleaned up. 3798 if (!jqLiteAcceptsData(element)) { 3799 return; 3800 } 3801 3802 var expandoStore = jqLiteExpandoStore(element, true); 3803 var events = expandoStore.events; 3804 var handle = expandoStore.handle; 3805 3806 if (!handle) { 3807 handle = expandoStore.handle = createEventHandler(element, events); 3808 } 3809 3810 // http://jsperf.com/string-indexof-vs-split 3811 var types = type.indexOf(' ') >= 0 ? type.split(' ') : [type]; 3812 var i = types.length; 3813 3814 var addHandler = function(type, specialHandlerWrapper, noEventListener) { 3815 var eventFns = events[type]; 3816 3817 if (!eventFns) { 3818 eventFns = events[type] = []; 3819 eventFns.specialHandlerWrapper = specialHandlerWrapper; 3820 if (type !== '$destroy' && !noEventListener) { 3821 element.addEventListener(type, handle); 3822 } 3823 } 3824 3825 eventFns.push(fn); 3826 }; 3827 3828 while (i--) { 3829 type = types[i]; 3830 if (MOUSE_EVENT_MAP[type]) { 3831 addHandler(MOUSE_EVENT_MAP[type], specialMouseHandlerWrapper); 3832 addHandler(type, undefined, true); 3833 } else { 3834 addHandler(type); 3835 } 3836 } 3837 }, 3838 3839 off: jqLiteOff, 3840 3841 one: function(element, type, fn) { 3842 element = jqLite(element); 3843 3844 //add the listener twice so that when it is called 3845 //you can remove the original function and still be 3846 //able to call element.off(ev, fn) normally 3847 element.on(type, function onFn() { 3848 element.off(type, fn); 3849 element.off(type, onFn); 3850 }); 3851 element.on(type, fn); 3852 }, 3853 3854 replaceWith: function(element, replaceNode) { 3855 var index, parent = element.parentNode; 3856 jqLiteDealoc(element); 3857 forEach(new JQLite(replaceNode), function(node) { 3858 if (index) { 3859 parent.insertBefore(node, index.nextSibling); 3860 } else { 3861 parent.replaceChild(node, element); 3862 } 3863 index = node; 3864 }); 3865 }, 3866 3867 children: function(element) { 3868 var children = []; 3869 forEach(element.childNodes, function(element) { 3870 if (element.nodeType === NODE_TYPE_ELEMENT) { 3871 children.push(element); 3872 } 3873 }); 3874 return children; 3875 }, 3876 3877 contents: function(element) { 3878 return element.contentDocument || element.childNodes || []; 3879 }, 3880 3881 append: function(element, node) { 3882 var nodeType = element.nodeType; 3883 if (nodeType !== NODE_TYPE_ELEMENT && nodeType !== NODE_TYPE_DOCUMENT_FRAGMENT) return; 3884 3885 node = new JQLite(node); 3886 3887 for (var i = 0, ii = node.length; i < ii; i++) { 3888 var child = node[i]; 3889 element.appendChild(child); 3890 } 3891 }, 3892 3893 prepend: function(element, node) { 3894 if (element.nodeType === NODE_TYPE_ELEMENT) { 3895 var index = element.firstChild; 3896 forEach(new JQLite(node), function(child) { 3897 element.insertBefore(child, index); 3898 }); 3899 } 3900 }, 3901 3902 wrap: function(element, wrapNode) { 3903 jqLiteWrapNode(element, jqLite(wrapNode).eq(0).clone()[0]); 3904 }, 3905 3906 remove: jqLiteRemove, 3907 3908 detach: function(element) { 3909 jqLiteRemove(element, true); 3910 }, 3911 3912 after: function(element, newElement) { 3913 var index = element, parent = element.parentNode; 3914 3915 if (parent) { 3916 newElement = new JQLite(newElement); 3917 3918 for (var i = 0, ii = newElement.length; i < ii; i++) { 3919 var node = newElement[i]; 3920 parent.insertBefore(node, index.nextSibling); 3921 index = node; 3922 } 3923 } 3924 }, 3925 3926 addClass: jqLiteAddClass, 3927 removeClass: jqLiteRemoveClass, 3928 3929 toggleClass: function(element, selector, condition) { 3930 if (selector) { 3931 forEach(selector.split(' '), function(className) { 3932 var classCondition = condition; 3933 if (isUndefined(classCondition)) { 3934 classCondition = !jqLiteHasClass(element, className); 3935 } 3936 (classCondition ? jqLiteAddClass : jqLiteRemoveClass)(element, className); 3937 }); 3938 } 3939 }, 3940 3941 parent: function(element) { 3942 var parent = element.parentNode; 3943 return parent && parent.nodeType !== NODE_TYPE_DOCUMENT_FRAGMENT ? parent : null; 3944 }, 3945 3946 next: function(element) { 3947 return element.nextElementSibling; 3948 }, 3949 3950 find: function(element, selector) { 3951 if (element.getElementsByTagName) { 3952 return element.getElementsByTagName(selector); 3953 } else { 3954 return []; 3955 } 3956 }, 3957 3958 clone: jqLiteClone, 3959 3960 triggerHandler: function(element, event, extraParameters) { 3961 3962 var dummyEvent, eventFnsCopy, handlerArgs; 3963 var eventName = event.type || event; 3964 var expandoStore = jqLiteExpandoStore(element); 3965 var events = expandoStore && expandoStore.events; 3966 var eventFns = events && events[eventName]; 3967 3968 if (eventFns) { 3969 // Create a dummy event to pass to the handlers 3970 dummyEvent = { 3971 preventDefault: function() { this.defaultPrevented = true; }, 3972 isDefaultPrevented: function() { return this.defaultPrevented === true; }, 3973 stopImmediatePropagation: function() { this.immediatePropagationStopped = true; }, 3974 isImmediatePropagationStopped: function() { return this.immediatePropagationStopped === true; }, 3975 stopPropagation: noop, 3976 type: eventName, 3977 target: element 3978 }; 3979 3980 // If a custom event was provided then extend our dummy event with it 3981 if (event.type) { 3982 dummyEvent = extend(dummyEvent, event); 3983 } 3984 3985 // Copy event handlers in case event handlers array is modified during execution. 3986 eventFnsCopy = shallowCopy(eventFns); 3987 handlerArgs = extraParameters ? [dummyEvent].concat(extraParameters) : [dummyEvent]; 3988 3989 forEach(eventFnsCopy, function(fn) { 3990 if (!dummyEvent.isImmediatePropagationStopped()) { 3991 fn.apply(element, handlerArgs); 3992 } 3993 }); 3994 } 3995 } 3996}, function(fn, name) { 3997 /** 3998 * chaining functions 3999 */ 4000 JQLite.prototype[name] = function(arg1, arg2, arg3) { 4001 var value; 4002 4003 for (var i = 0, ii = this.length; i < ii; i++) { 4004 if (isUndefined(value)) { 4005 value = fn(this[i], arg1, arg2, arg3); 4006 if (isDefined(value)) { 4007 // any function which returns a value needs to be wrapped 4008 value = jqLite(value); 4009 } 4010 } else { 4011 jqLiteAddNodes(value, fn(this[i], arg1, arg2, arg3)); 4012 } 4013 } 4014 return isDefined(value) ? value : this; 4015 }; 4016}); 4017 4018// bind legacy bind/unbind to on/off 4019JQLite.prototype.bind = JQLite.prototype.on; 4020JQLite.prototype.unbind = JQLite.prototype.off; 4021 4022 4023// Provider for private $$jqLite service 4024/** @this */ 4025function $$jqLiteProvider() { 4026 this.$get = function $$jqLite() { 4027 return extend(JQLite, { 4028 hasClass: function(node, classes) { 4029 if (node.attr) node = node[0]; 4030 return jqLiteHasClass(node, classes); 4031 }, 4032 addClass: function(node, classes) { 4033 if (node.attr) node = node[0]; 4034 return jqLiteAddClass(node, classes); 4035 }, 4036 removeClass: function(node, classes) { 4037 if (node.attr) node = node[0]; 4038 return jqLiteRemoveClass(node, classes); 4039 } 4040 }); 4041 }; 4042} 4043 4044/** 4045 * Computes a hash of an 'obj'. 4046 * Hash of a: 4047 * string is string 4048 * number is number as string 4049 * object is either result of calling $$hashKey function on the object or uniquely generated id, 4050 * that is also assigned to the $$hashKey property of the object. 4051 * 4052 * @param obj 4053 * @returns {string} hash string such that the same input will have the same hash string. 4054 * The resulting string key is in 'type:hashKey' format. 4055 */ 4056function hashKey(obj, nextUidFn) { 4057 var key = obj && obj.$$hashKey; 4058 4059 if (key) { 4060 if (typeof key === 'function') { 4061 key = obj.$$hashKey(); 4062 } 4063 return key; 4064 } 4065 4066 var objType = typeof obj; 4067 if (objType === 'function' || (objType === 'object' && obj !== null)) { 4068 key = obj.$$hashKey = objType + ':' + (nextUidFn || nextUid)(); 4069 } else { 4070 key = objType + ':' + obj; 4071 } 4072 4073 return key; 4074} 4075 4076// A minimal ES2015 Map implementation. 4077// Should be bug/feature equivalent to the native implementations of supported browsers 4078// (for the features required in Angular). 4079// See https://kangax.github.io/compat-table/es6/#test-Map 4080var nanKey = Object.create(null); 4081function NgMapShim() { 4082 this._keys = []; 4083 this._values = []; 4084 this._lastKey = NaN; 4085 this._lastIndex = -1; 4086} 4087NgMapShim.prototype = { 4088 _idx: function(key) { 4089 if (key
vendor: 1,720 bytes, lines 4089-4153
4089=== this._lastKey) { 4090 return this._lastIndex; 4091 } 4092 this._lastKey = key; 4093 this._lastIndex = this._keys.indexOf(key); 4094 return this._lastIndex; 4095 }, 4096 _transformKey: function(key) { 4097 return isNumberNaN(key) ? nanKey : key; 4098 }, 4099 get: function(key) { 4100 key = this._transformKey(key); 4101 var idx = this._idx(key); 4102 if (idx !== -1) { 4103 return this._values[idx]; 4104 } 4105 }, 4106 set: function(key, value) { 4107 key = this._transformKey(key); 4108 var idx = this._idx(key); 4109 if (idx === -1) { 4110 idx = this._lastIndex = this._keys.length; 4111 } 4112 this._keys[idx] = key; 4113 this._values[idx] = value; 4114 4115 // Support: IE11 4116 // Do not `return this` to simulate the partial IE11 implementation 4117 }, 4118 delete: function(key) { 4119 key = this._transformKey(key); 4120 var idx = this._idx(key); 4121 if (idx === -1) { 4122 return false; 4123 } 4124 this._keys.splice(idx, 1); 4125 this._values.splice(idx, 1); 4126 this._lastKey = NaN; 4127 this._lastIndex = -1; 4128 return true; 4129 } 4130}; 4131 4132// For now, always use `NgMapShim`, even if `window.Map` is available. Some native implementations 4133// are still buggy (often in subtle ways) and can cause hard-to-debug failures. When native `Map` 4134// implementations get more stable, we can reconsider switching to `window.Map` (when available). 4135var NgMap = NgMapShim; 4136 4137var $$MapProvider = [/** @this */function() { 4138 this.$get = [function() { 4139 return NgMap; 4140 }]; 4141}]; 4142 4143/** 4144 * @ngdoc function 4145 * @module ng 4146 * @name angular.injector 4147 * @kind function 4148 * 4149 * @description 4150 * Creates an injector object that can be used for retrieving services as well as for 4151 * dependency injection (see {@link guide/di dependency injection}). 4152 * 4153 * @param {Array.<string|Function>}
4153 modules A list of module functions or their aliases. See 4154 * {@link angular.module}. The `ng` module must be explicitly added. 4155 * @param {boolean=} [strictDi=false] Whether the injector should be in strict mode, which 4156 * disallows argument name annotation inference. 4157 * @returns {injector} Injector object. See {@link auto.$injector $injector}. 4158 * 4159 * @example 4160 * Typical usage 4161 * ```js 4162 * // create an injector 4163 * var $injector = angular.injector(['ng']); 4164 * 4165 * // use the injector to kick off your application 4166 * // use the type inference to auto inject arguments, or use implicit injection 4167 * $injector.invoke(function($rootScope, $compile, $document) { 4168 * $compile($document)($rootScope); 4169 * $rootScope.$digest(); 4170 * }); 4171 * ``` 4172 * 4173 * Sometimes you want to get access to the injector of a currently running Angular app 4174 * from outside Angular. Perhaps, you want to inject and compile some markup after the 4175 * application has been bootstrapped. You can do this using the extra `injector()` added 4176 * to JQuery/jqLite elements. See {@link angular.element}. 4177 * 4178 * *This is fairly rare but could be the case if a third party library is injecting the 4179 * markup.* 4180 * 4181 * In the following example a new block of HTML containing a `ng-controller` 4182 * directive is added to the end of the document body by JQuery. We then compile and link 4183 * it into the current AngularJS scope. 4184 * 4185 * ```js 4186 * var $div = $('<div ng-controller="MyCtrl">{{content.label}}</div>'); 4187 * $(document.body).append($div); 4188 * 4189 * angular.element(document).injector().invoke(function($compile) { 4190 * var scope = angular.element($div).scope(); 4191 * $compile($div)(scope); 4192 * }); 4193 * ``` 4194 */ 4195 4196 4197/** 4198 * @ngdoc module 4199 * @name auto 4200 * @installation 4201 * @description 4202 * 4203 * Implicit module which gets automatically added to each {@link auto.$injector $injector}. 4204 */ 4205 4206var ARROW_ARG = /^([^(]+?)=>/; 4207var FN_ARGS = /^[^(]*\(\s*([^)]*)\)/m; 4208var FN_ARG_SPLIT = /,/; 4209var FN_ARG = /^\s*(_?)(\S+?)\1\s*$/; 4210var STRIP_COMMENTS = /((\/\/.*$)|(\/\*[\s\S]*?\*\/))/mg; 4211var $injectorMinErr = minErr('$injector'); 4212 4213function stringifyFn(fn) { 4214 return Function.prototype.toString.call(fn); 4215} 4216 4217function extractArgs(fn) { 4218 var fnText = stringifyFn(fn).replace(STRIP_COMMENTS, ''), 4219 args = fnText.match(ARROW_ARG) || fnText.match(FN_ARGS); 4220 return args; 4221} 4222 4223function anonFn(fn) { 4224 // For anonymous functions, showing at the very least the function signature can help in 4225 // debugging. 4226 var args = extractArgs(fn); 4227 if (args) { 4228 return 'function(' + (args[1] || '').replace(/[\s\r\n]+/, ' ') + ')'; 4229 } 4230 return 'fn'; 4231} 4232 4233function annotate(fn, strictDi, name) { 4234 var $inject, 4235 argDecl, 4236 last; 4237 4238 if (typeof fn === 'function') { 4239 if (!($inject = fn.$inject)) { 4240 $inject = []; 4241 if (fn.length) { 4242 if (strictDi) { 4243 if (!isString(name) || !name) { 4244 name = fn.name || anonFn(fn); 4245 } 4246 throw $injectorMinErr('strictdi', 4247 '{0} is not using explicit annotation and cannot be invoked in strict mode', name); 4248 } 4249 argDecl = extractArgs(fn); 4250 forEach(argDecl[1].split(FN_ARG_SPLIT), function(arg) { 4251 arg.replace(FN_ARG, function(all, underscore, name) { 4252 $inject.push(name); 4253 }); 4254 }); 4255 } 4256 fn.$inject = $inject; 4257 } 4258 } else if (isArray(fn)) { 4259 last = fn.length - 1; 4260 assertArgFn(fn[last], 'fn'); 4261 $inject = fn.slice(0, last); 4262 } else { 4263 assertArgFn(fn, 'fn', true); 4264 } 4265 return $inject; 4266} 4267 4268/////////////////////////////////////// 4269 4270/** 4271 * @ngdoc service 4272 * @name $injector 4273 * 4274 * @description 4275 * 4276 * `$injector` is used to retrieve object instances as defined by 4277 * {@link auto.$provide provider}, instantiate types, invoke methods, 4278 * and load modules. 4279 * 4280 * The following always holds true: 4281 * 4282 * ```js 4283 * var $injector = angular.injector(); 4284 * expect($injector.get('$injector')).toBe($injector); 4285 * expect($injector.invoke(function($injector) { 4286 * return $injector; 4287 * })).toBe($injector); 4288 * ``` 4289 * 4290 * # Injection Function Annotation 4291 * 4292 * JavaScript does not have annotations, and annotations are needed for dependency injection. The 4293 * following are all valid ways of annotating function with injection arguments and are equivalent. 4294 * 4295 * ```js 4296 * // inferred (only works if code not minified/obfuscated) 4297 * $injector.invoke(function(serviceA){}); 4298 * 4299 * // annotated 4300 * function explicit(serviceA) {}; 4301 * explicit.$inject = ['serviceA']; 4302 * $injector.invoke(explicit); 4303 * 4304 * // inline 4305 * $injector.invoke(['serviceA', function(serviceA){}]); 4306 * ``` 4307 * 4308 * ## Inference 4309 * 4310 * In JavaScript calling `toString()` on a function returns the function definition. The definition 4311 * can then be parsed and the function arguments can be extracted. This method of discovering 4312 * annotations is disallowed when the injector is in strict mode. 4313 * *NOTE:* This does not work with minification, and obfuscation tools since these tools change the 4314 * argument names. 4315 * 4316 * ## `$inject` Annotation 4317 * By adding an `$inject` property onto a function the injection parameters can be specified. 4318 * 4319 * ## Inline 4320 * As an array of injection names, where the last item in the array is the function to call. 4321 */ 4322 4323/** 4324 * @ngdoc property 4325 * @name $injector#modules 4326 * @type {Object} 4327 * @description 4328 * A hash containing all the modules that have been loaded into the 4329 * $injector. 4330 * 4331 * You can use this property to find out information about a module via the 4332 * {@link angular.Module#info `myModule.info(...)`} method. 4333 * 4334 * For example: 4335 * 4336 * ``` 4337 * var info = $injector.modules['ngAnimate'].info(); 4338 * ``` 4339 * 4340 * **Do not use this property to attempt to modify the modules after the application 4341 * has been bootstrapped.** 4342 */ 4343 4344 4345/** 4346 * @ngdoc method 4347 * @name $injector#get 4348 * 4349 * @description 4350 * Return an instance of the service. 4351 * 4352 * @param {string} name The name of the instance to retrieve. 4353 * @param {string=} caller An optional string to provide the origin of the function call for error messages. 4354 * @return {*} The instance. 4355 */ 4356 4357/** 4358 * @ngdoc method 4359 * @name $injector#invoke 4360 * 4361 * @description 4362 * Invoke the method and supply the method arguments from the `$injector`. 4363 * 4364 * @param {Function|Array.<string|Function>} fn The injectable function to invoke. Function parameters are 4365 * injected according to the {@link guide/di $inject Annotation} rules. 4366 * @param {Object=} self The `this` for the invoked method. 4367 * @param {Object=} locals Optional object. If preset then any argument names are read from this 4368 * object first, before the `$injector` is consulted. 4369 * @returns {*} the value returned by the invoked `fn` function. 4370 */ 4371 4372/** 4373 * @ngdoc method 4374 * @name $injector#has 4375 * 4376 * @description 4377 * Allows the user to query if the particular service exists. 4378 * 4379 * @param {string} name Name of the service to query. 4380 * @returns {boolean} `true` if injector has given service. 4381 */ 4382 4383/** 4384 * @ngdoc method 4385 * @name $injector#instantiate 4386 * @description 4387 * Create a new instance of JS type. The method takes a constructor function, invokes the new 4388 * operator, and supplies all of the arguments to the constructor function as specified by the 4389 * constructor annotation. 4390 * 4391 * @param {Function} Type Annotated constructor function. 4392 * @param {Object=} locals Optional object. If preset then any argument names are read from this 4393 * object first, before the `$injector` is consulted. 4394 * @returns {Object} new instance of `Type`. 4395 */ 4396 4397/** 4398 * @ngdoc method 4399 * @name $injector#annotate 4400 * 4401 * @description 4402 * Returns an array of service names which the function is requesting for injection. This API is 4403 * used by the injector to determine which services need to be injected into the function when the 4404 * function is invoked. There are three ways in which the function can be annotated with the needed 4405 * dependencies. 4406 * 4407 * # Argument names 4408 * 4409 * The simplest form is to extract the dependencies from the arguments of the function. This is done
4410 * by converting the function into a string using `toString()` method and extracting the argument 4411 * names. 4412 * ```js 4413 * // Given 4414 * function MyController($scope, $route) { 4415 * // ... 4416 * } 4417 * 4418 * // Then 4419 * expect(injector.annotate(MyController)).toEqual(['$scope', '$route']); 4420 * ``` 4421 * 4422 * You can disallow this method by using strict injection mode. 4423 * 4424 * This method does not work with code minification / obfuscation. For this reason the following 4425 * annotation strategies are supported. 4426 * 4427 * # The `$inject` property 4428 * 4429 * If a function has an `$inject` property and its value is an array of strings, then the strings 4430 * represent names of services to be injected into the function. 4431 * ```js 4432 * // Given 4433 * var MyController = function(obfuscatedScope, obfuscatedRoute) { 4434 * // ... 4435 * } 4436 * // Define function dependencies 4437 * MyController['$inject'] = ['$scope', '$route']; 4438 * 4439 * // Then 4440 * expect(injector.annotate(MyController)).toEqual(['$scope', '$route']); 4441 * ``` 4442 * 4443 * # The array notation 4444 * 4445 * It is often desirable to inline Injected functions and that's when setting the `$inject` property 4446 * is very inconvenient. In these situations using the array notation to specify the dependencies in 4447 * a way that survives minification is a better choice: 4448 * 4449 * ```js 4450 * // We wish to write this (not minification / obfuscation safe) 4451 * injector.invoke(function($compile, $rootScope) { 4452 * // ... 4453 * }); 4454 * 4455 * // We are forced to write break inlining 4456 * var tmpFn = function(obfuscatedCompile, obfuscatedRootScope) { 4457 * // ... 4458 * }; 4459 * tmpFn.$inject = ['$compile', '$rootScope']; 4460 * injector.invoke(tmpFn); 4461 * 4462 * // To better support inline function the inline annotation is supported 4463 * injector.invoke(['$compile', '$rootScope', function(obfCompile, obfRootScope) { 4464 * // ... 4465 * }]); 4466 * 4467 * // Therefore 4468 * expect(injector.annotate( 4469 * ['$compile', '$rootScope', function(obfus_$compile, obfus_$rootScope) {}]) 4470 * ).toEqual(['$compile', '$rootScope']); 4471 * ``` 4472 * 4473 * @param {Function|Array.<string|Function>} fn Function for which dependent service names need to 4474 * be retrieved as described above. 4475 * 4476 * @param {boolean=} [strictDi=false] Disallow argument name annotation inference. 4477 * 4478 * @returns {Array.<string>} The names of the services which the function requires. 4479 */ 4480 4481 4482 4483/** 4484 * @ngdoc service 4485 * @name $provide 4486 * 4487 * @description 4488 * 4489 * The {@link auto.$provide $provide} service has a number of methods for registering components 4490 * with the {@link auto.$injector $injector}. Many of these functions are also exposed on 4491 * {@link angular.Module}. 4492 * 4493 * An Angular **service** is a singleton object created by a **service factory**. These **service 4494 * factories** are functions which, in turn, are created by a **service provider**. 4495 * The **service providers** are constructor functions. When instantiated they must contain a 4496 * property called `$get`, which holds the **service factory** function. 4497 * 4498 * When you request a service, the {@link auto.$injector $injector} is responsible for finding the 4499 * correct **service provider**, instantiating it and then calling its `$get` **service factory** 4500 * function to get the instance of the **service**. 4501 * 4502 * Often services have no configuration options and there is no need to add methods to the service 4503 * provider. The provider will be no more than a constructor function with a `$get` property. For 4504 * these cases the {@link auto.$provide $provide} service has additional helper methods to register 4505 * services without specifying a provider. 4506 * 4507 * * {@link auto.$provide#provider provider(name, provider)} - registers a **service provider** with the 4508 * {@link auto.$injector $injector} 4509 * * {@link auto.$provide#constant constant(name, obj)} - registers a value/object that can be accessed by 4510 * providers and services. 4511 * * {@link auto.$provide#value value(name, obj)} - registers a value/object that can only be accessed by 4512 * services, not providers. 4513 * * {@link auto.$provide#factory factory(name, fn)} - registers a service **factory function** 4514 * that will be wrapped in a **service provider** object, whose `$get` property will contain the 4515 * given factory function. 4516 * * {@link auto.$provide#service service(name, Fn)} - registers a **constructor function** 4517 * that will be wrapped in a **service provider** object, whose `$get` property will instantiate 4518 * a new object using the given constructor function. 4519 * * {@link auto.$provide#decorator decorator(name, decorFn)} - registers a **decorator function** that 4520 * will be able to modify or replace the implementation of another service. 4521 * 4522 * See the individual methods for more information and examples. 4523 */ 4524 4525/** 4526 * @ngdoc method 4527 * @name $provide#provider 4528 * @description 4529 * 4530 * Register a **provider function** with the {@link auto.$injector $injector}. Provider functions 4531 * are constructor functions, whose instances are responsible for "providing" a factory for a 4532 * service. 4533 * 4534 * Service provider names start with the name of the service they provide followed by `Provider`. 4535 * For example, the {@link ng.$log $log} service has a provider called 4536 * {@link ng.$logProvider $logProvider}. 4537 * 4538 * Service provider objects can have additional methods which allow configuration of the provider 4539 * and its service. Importantly, you can configure what kind of service is created by the `$get` 4540 * method, or how that service will act. For example, the {@link ng.$logProvider $logProvider} has a 4541 * method {@link ng.$logProvider#debugEnabled debugEnabled} 4542 * which lets you specify whether the {@link ng.$log $log} service will log debug messages to the 4543 * console or not. 4544 * 4545 * @param {string} name The name of the instance. NOTE: the provider will be available under `name + 4546 'Provider'` key. 4547 * @param {(Object|function())} provider If the provider is: 4548 * 4549 * - `Object`: then it should have a `$get` method. The `$get` method will be invoked using 4550 * {@link auto.$injector#invoke $injector.invoke()} when an instance needs to be created. 4551 * - `Constructor`: a new instance of the provider will be created using 4552 * {@link auto.$injector#instantiate $injector.instantiate()}, then treated as `object`. 4553 * 4554 * @returns {Object} registered provider instance 4555 4556 * @example 4557 * 4558 * The following example shows how to create a simple event tracking service and register it using 4559 * {@link auto.$provide#provider $provide.provider()}. 4560 * 4561 * ```js 4562 * // Define the eventTracker provider 4563 * function EventTrackerProvider() { 4564 * var trackingUrl = '/track'; 4565 * 4566 * // A provider method for configuring where the tracked events should been saved 4567 * this.setTrackingUrl = function(url) { 4568 * trackingUrl = url; 4569 * }; 4570 * 4571 * // The service factory function 4572 * this.$get = ['$http', function($http) { 4573 * var trackedEvents = {}; 4574 * return { 4575 * // Call this to track an event 4576 * event: function(event) { 4577 * var count = trackedEvents[event] || 0; 4578 * count += 1; 4579 * trackedEvents[event] = count; 4580 * return count; 4581 * }, 4582 * // Call this to save the tracked events to the trackingUrl 4583 * save: function() { 4584 * $http.post(trackingUrl, trackedEvents); 4585 * } 4586 * }; 4587 * }]; 4588 * } 4589 * 4590 * describe('eventTracker', function() { 4591 * var postSpy; 4592 * 4593 * beforeEach(module(function($provide) { 4594 * // Register the eventTracker provider 4595 * $provide.provider('eventTracker', EventTrackerProvider); 4596 * })); 4597 * 4598 * beforeEach(module(function(eventTrackerProvider) { 4599 * // Configure eventTracker provider 4600 * eventTrackerProvider.setTrackingUrl('/custom-track'); 4601 * })); 4602 * 4603 * it('tracks events', inject(function(eventTracker) { 4604 * expect(eventTracker.event('login')).toEqual(1); 4605 * expect(eventTracker.event('login')).toEqual(2); 4606 * })); 4607 * 4608 * it('saves to the tracking url', inject(function(eventTracker, $http) { 4609 * postSpy = spyOn($http, 'post'); 4610 * eventTracker.event('login'); 4611 * eventTracker.save(); 4612 * expect(postSpy).toHaveBeenCalled(); 4613 * expect(postSpy.mostRecentCall.args[0]).not.toEqual('/track'); 4614 * expect(postSpy.mostRecentCall.args[0]).toEqual('/custom-track'); 4615 * expect(postSpy.mostRecentCall.args[1]).toEqual({ 'login': 1 }); 4616 * })); 4617 * }); 4618 * ``` 4619 */ 4620 4621/** 4622 * @ngdoc method 4623 * @name $provide#factory 4624 * @description 4625 * 4626 * Register a **service factory**, which will be called to return the service instance. 4627 * This is short for registering a service where its provider consists of only a `$get` property, 4628 * which is the given service factory function. 4629 * You should use {@link auto.$provide#factory $provide.factory(getFn)} if you do not need to 4630 * configure your service in a provider. 4631 * 4632 * @param {string} name The name of the instance. 4633 * @param {Function|Array.<string|Function>} $getFn The injectable $getFn for the instance creation. 4634 * Internally this is a short hand for `$provide.provider(name, {$get: $getFn})`. 4635 * @returns {Object} registered provider instance 4636 * 4637 * @example 4638 * Here is an example of registering a service 4639 * ```js 4640 * $provide.factory('ping', ['$http', function($http) { 4641 * return function ping() { 4642 * return $http.send('/ping'); 4643 * }; 4644 * }]); 4645 * ``` 4646 * You would then inject and use this service like this: 4647 * ```js 4648 * someModule.controller('Ctrl', ['ping', function(ping) { 4649 * ping(); 4650 * }]); 4651 * ``` 4652 */ 4653 4654 4655/** 4656 * @ngdoc method 4657 * @name $provide#service 4658 * @description 4659 * 4660 * Register a **service constructor**, which will be invoked with `new` to create the service 4661 * instance. 4662 * This is short for registering a service where its provider's `$get` property is a factory 4663 * function that returns an instance instantiated by the injector from the service constructor 4664 * function. 4665 * 4666 * Internally it looks a bit like this: 4667 * 4668 * ``` 4669 * { 4670 * $get: function() { 4671 * return $injector.instantiate(constructor); 4672 * } 4673 * } 4674 * ``` 4675 * 4676 * 4677 * You should use {@link auto.$provide#service $provide.service(class)} if you define your service 4678 * as a type/class. 4679 * 4680 * @param {string} name The name of the instance. 4681 * @param {Function|Array.<string|Function>} constructor An injectable class (constructor function) 4682 * that will be instantiated. 4683 * @returns {Object} registered provider instance 4684 * 4685 * @example 4686 * Here is an example of registering a service using 4687 * {@link auto.$provide#service $provide.service(class)}. 4688 * ```js 4689 * var Ping = function($http) { 4690 * this.$http = $http; 4691 * }; 4692 * 4693 * Ping.$inject = ['$http']; 4694 * 4695 * Ping.prototype.send = function() { 4696 * return this.$http.get('/ping'); 4697 * }; 4698 * $provide.service('ping', Ping); 4699 * ``` 4700 * You would then inject and use this service like this: 4701 * ```js 4702 * someModule.controller('Ctrl', ['ping', function(ping) { 4703 * ping.send(); 4704 * }]); 4705 * ``` 4706 */ 4707 4708 4709/** 4710 * @ngdoc method 4711 * @name $provide#value 4712 * @description 4713 * 4714 * Register a **value service** with the {@link auto.$injector $injector}, such as a string, a 4715 * number, an array, an object or a function. This is short for registering a service where its 4716 * provider's `$get` property is a factory function that takes no arguments and returns the **value 4717 * service**. That also means it is not possible to inject other services into a value service. 4718 * 4719 * Value services are similar to constant services, except that they cannot be injected into a 4720 * module configuration function (see {@link angular.Module#config}) but they can be overridden by 4721 * an Angular {@link auto.$provide#decorator decorator}. 4722 * 4723 * @param {string} name The name of the instance. 4724 * @param {*} value The value. 4725 * @returns {Object} registered provider instance 4726 * 4727 * @example 4728 * Here are some examples of creating value services. 4729 * ```js 4730 * $provide.value('ADMIN_USER', 'admin'); 4731 *
4732 * $provide.value('RoleLookup', { admin: 0, writer: 1, reader: 2 }); 4733 * 4734 * $provide.value('halfOf', function(value) { 4735 * return value / 2; 4736 * }); 4737 * ``` 4738 */ 4739 4740 4741/** 4742 * @ngdoc method 4743 * @name $provide#constant 4744 * @description 4745 * 4746 * Register a **constant service** with the {@link auto.$injector $injector}, such as a string, 4747 * a number, an array, an object or a function. Like the {@link auto.$provide#value value}, it is not 4748 * possible to inject other services into a constant. 4749 * 4750 * But unlike {@link auto.$provide#value value}, a constant can be 4751 * injected into a module configuration function (see {@link angular.Module#config}) and it cannot 4752 * be overridden by an Angular {@link auto.$provide#decorator decorator}. 4753 * 4754 * @param {string} name The name of the constant. 4755 * @param {*} value The constant value. 4756 * @returns {Object} registered instance 4757 * 4758 * @example 4759 * Here a some examples of creating constants: 4760 * ```js 4761 * $provide.constant('SHARD_HEIGHT', 306); 4762 * 4763 * $provide.constant('MY_COLOURS', ['red', 'blue', 'grey']); 4764 * 4765 * $provide.constant('double', function(value) { 4766 * return value * 2; 4767 * }); 4768 * ``` 4769 */ 4770 4771 4772/** 4773 * @ngdoc method 4774 * @name $provide#decorator 4775 * @description 4776 * 4777 * Register a **decorator function** with the {@link auto.$injector $injector}. A decorator function 4778 * intercepts the creation of a service, allowing it to override or modify the behavior of the 4779 * service. The return value of the decorator function may be the original service, or a new service 4780 * that replaces (or wraps and delegates to) the original service. 4781 * 4782 * You can find out more about using decorators in the {@link guide/decorators} guide. 4783 * 4784 * @param {string} name The name of the service to decorate. 4785 * @param {Function|Array.<string|Function>} decorator This function will be invoked when the service needs to be 4786 * provided and should return the decorated service instance. The function is called using 4787 * the {@link auto.$injector#invoke injector.invoke} method and is therefore fully injectable. 4788 * Local injection arguments: 4789 * 4790 * * `$delegate` - The original service instance, which can be replaced, monkey patched, configured, 4791 * decorated or delegated to. 4792 * 4793 * @example 4794 * Here we decorate the {@link ng.$log $log} service to convert warnings to errors by intercepting 4795 * calls to {@link ng.$log#error $log.warn()}. 4796 * ```js 4797 * $provide.decorator('$log', ['$delegate', function($delegate) { 4798 * $delegate.warn = $delegate.error; 4799 * return $delegate; 4800 * }]); 4801 * ``` 4802 */ 4803 4804 4805function createInjector(modulesToLoad, strictDi) { 4806 strictDi = (strictDi === true); 4807 var INSTANTIATING = {}, 4808 providerSuffix = 'Provider', 4809 path = [], 4810 loadedModules = new NgMap(), 4811 providerCache = { 4812 $provide: { 4813 provider: supportObject(provider), 4814 factory: supportObject(factory), 4815 service: supportObject(service), 4816 value: supportObject(value), 4817 constant: supportObject(constant), 4818 decorator: decorator 4819 } 4820 }, 4821 providerInjector = (providerCache.$injector = 4822 createInternalInjector(providerCache, function(serviceName, caller) { 4823 if (angular.isString(caller)) { 4824 path.push(caller); 4825 } 4826 throw $injectorMinErr('unpr', 'Unknown provider: {0}', path.join(' <- ')); 4827 })), 4828 instanceCache = {}, 4829 protoInstanceInjector = 4830 createInternalInjector(instanceCache, function(serviceName, caller) { 4831 var provider = providerInjector.get(serviceName + providerSuffix, caller); 4832 return instanceInjector.invoke( 4833 provider.$get, provider, undefined, serviceName); 4834 }), 4835 instanceInjector = protoInstanceInjector; 4836 4837 providerCache['$injector' + providerSuffix] = { $get: valueFn(protoInstanceInjector) }; 4838 instanceInjector.modules = providerInjector.modules = createMap(); 4839 var runBlocks = loadModules(modulesToLoad); 4840 instanceInjector = protoInstanceInjector.get('$injector'); 4841 instanceInjector.strictDi = strictDi; 4842 forEach(runBlocks, function(fn) { if (fn) instanceInjector.invoke(fn); }); 4843 4844 return instanceInjector; 4845 4846 //////////////////////////////////// 4847 // $provider 4848 //////////////////////////////////// 4849 4850 function supportObject(delegate) { 4851 return function(key, value) { 4852 if (isObject(key)) {
vendor: 5,894 bytes, lines 4853-5021
4853 forEach(key, reverseParams(delegate)); 4854 } else { 4855 return delegate(key, value); 4856 } 4857 }; 4858 } 4859 4860 function provider(name, provider_) { 4861 assertNotHasOwnProperty(name, 'service'); 4862 if (isFunction(provider_) || isArray(provider_)) { 4863 provider_ = providerInjector.instantiate(provider_); 4864 } 4865 if (!provider_.$get) { 4866 throw $injectorMinErr('pget', 'Provider \'{0}\' must define $get factory method.', name); 4867 } 4868 return (providerCache[name + providerSuffix] = provider_); 4869 } 4870 4871 function enforceReturnValue(name, factory) { 4872 return /** @this */ function enforcedReturnValue() { 4873 var result = instanceInjector.invoke(factory, this); 4874 if (isUndefined(result)) { 4875 throw $injectorMinErr('undef', 'Provider \'{0}\' must return a value from $get factory method.', name); 4876 } 4877 return result; 4878 }; 4879 } 4880 4881 function factory(name, factoryFn, enforce) { 4882 return provider(name, { 4883 $get: enforce !== false ? enforceReturnValue(name, factoryFn) : factoryFn 4884 }); 4885 } 4886 4887 function service(name, constructor) { 4888 return factory(name, ['$injector', function($injector) { 4889 return $injector.instantiate(constructor); 4890 }]); 4891 } 4892 4893 function value(name, val) { return factory(name, valueFn(val), false); } 4894 4895 function constant(name, value) { 4896 assertNotHasOwnProperty(name, 'constant'); 4897 providerCache[name] = value; 4898 instanceCache[name] = value; 4899 } 4900 4901 function decorator(serviceName, decorFn) { 4902 var origProvider = providerInjector.get(serviceName + providerSuffix), 4903 orig$get = origProvider.$get; 4904 4905 origProvider.$get = function() { 4906 var origInstance = instanceInjector.invoke(orig$get, origProvider); 4907 return instanceInjector.invoke(decorFn, null, {$delegate: origInstance}); 4908 }; 4909 } 4910 4911 //////////////////////////////////// 4912 // Module Loading 4913 //////////////////////////////////// 4914 function loadModules(modulesToLoad) { 4915 assertArg(isUndefined(modulesToLoad) || isArray(modulesToLoad), 'modulesToLoad', 'not an array'); 4916 var runBlocks = [], moduleFn; 4917 forEach(modulesToLoad, function(module) { 4918 if (loadedModules.get(module)) return; 4919 loadedModules.set(module, true); 4920 4921 function runInvokeQueue(queue) { 4922 var i, ii; 4923 for (i = 0, ii = queue.length; i < ii; i++) { 4924 var invokeArgs = queue[i], 4925 provider = providerInjector.get(invokeArgs[0]); 4926 4927 provider[invokeArgs[1]].apply(provider, invokeArgs[2]); 4928 } 4929 } 4930 4931 try { 4932 if (isString(module)) { 4933 moduleFn = angularModule(module); 4934 instanceInjector.modules[module] = moduleFn; 4935 runBlocks = runBlocks.concat(loadModules(moduleFn.requires)).concat(moduleFn._runBlocks); 4936 runInvokeQueue(moduleFn._invokeQueue); 4937 runInvokeQueue(moduleFn._configBlocks); 4938 } else if (isFunction(module)) { 4939 runBlocks.push(providerInjector.invoke(module)); 4940 } else if (isArray(module)) { 4941 runBlocks.push(providerInjector.invoke(module)); 4942 } else { 4943 assertArgFn(module, 'module'); 4944 } 4945 } catch (e) { 4946 if (isArray(module)) { 4947 module = module[module.length - 1]; 4948 } 4949 if (e.message && e.stack && e.stack.indexOf(e.message) === -1) { 4950 // Safari & FF's stack traces don't contain error.message content 4951 // unlike those of Chrome and IE 4952 // So if stack doesn't contain message, we create a new string that contains both. 4953 // Since error.stack is read-only in Safari, I'm overriding e and not e.stack here. 4954 // eslint-disable-next-line no-ex-assign 4955 e = e.message + '\n' + e.stack; 4956 } 4957 throw $injectorMinErr('modulerr', 'Failed to instantiate module {0} due to:\n{1}', 4958 module, e.stack || e.message || e); 4959 } 4960 }); 4961 return runBlocks; 4962 } 4963 4964 //////////////////////////////////// 4965 // internal Injector 4966 //////////////////////////////////// 4967 4968 function createInternalInjector(cache, factory) { 4969 4970 function getService(serviceName, caller) { 4971 if (cache.hasOwnProperty(serviceName)) { 4972 if (cache[serviceName] === INSTANTIATING) { 4973 throw $injectorMinErr('cdep', 'Circular dependency found: {0}', 4974 serviceName + ' <- ' + path.join(' <- ')); 4975 } 4976 return cache[serviceName]; 4977 } else { 4978 try { 4979 path.unshift(serviceName); 4980 cache[serviceName] = INSTANTIATING; 4981 cache[serviceName] = factory(serviceName, caller); 4982 return cache[serviceName]; 4983 } catch (err) { 4984 if (cache[serviceName] === INSTANTIATING) { 4985 delete cache[serviceName]; 4986 } 4987 throw err; 4988 } finally { 4989 path.shift(); 4990 } 4991 } 4992 } 4993 4994 4995 function injectionArgs(fn, locals, serviceName) { 4996 var args = [], 4997 $inject = createInjector.$$annotate(fn, strictDi, serviceName); 4998 4999 for (var i = 0, length = $inject.length; i < length; i++) { 5000 var key = $inject[i]; 5001 if (typeof key !== 'string') { 5002 throw $injectorMinErr('itkn', 5003 'Incorrect injection token! Expected service name as string, got {0}', key); 5004 } 5005 args.push(locals && locals.hasOwnProperty(key) ? locals[key] : 5006 getService(key, serviceName)); 5007 } 5008 return args; 5009 } 5010 5011 function isClass(func) { 5012 // Support: IE 9-11 only 5013 // IE 9-11 do not support classes and IE9 leaks with the code below. 5014 if (msie || typeof func !== 'function') { 5015 return false; 5016 } 5017 var result = func.$$ngIsClass; 5018 if (!isBoolean(result)) { 5019 // Support: Edge 12-13 only 5020 // See: https://developer.microsoft.com/en-us/microsoft-edge/platform/issues/6156135/ 5021 result = func.$$ngIsClass = /^(?:class\b|constructor\()
vendor: 25,211 bytes, lines 5021-5715
5021/.test(stringifyFn(func)); 5022 } 5023 return result; 5024 } 5025 5026 function invoke(fn, self, locals, serviceName) { 5027 if (typeof locals === 'string') { 5028 serviceName = locals; 5029 locals = null; 5030 } 5031 5032 var args = injectionArgs(fn, locals, serviceName); 5033 if (isArray(fn)) { 5034 fn = fn[fn.length - 1]; 5035 } 5036 5037 if (!isClass(fn)) { 5038 // http://jsperf.com/angularjs-invoke-apply-vs-switch 5039 // #5388 5040 return fn.apply(self, args); 5041 } else { 5042 args.unshift(null); 5043 return new (Function.prototype.bind.apply(fn, args))(); 5044 } 5045 } 5046 5047 5048 function instantiate(Type, locals, serviceName) { 5049 // Check if Type is annotated and use just the given function at n-1 as parameter 5050 // e.g. someModule.factory('greeter', ['$window', function(renamed$window) {}]); 5051 var ctor = (isArray(Type) ? Type[Type.length - 1] : Type); 5052 var args = injectionArgs(Type, locals, serviceName); 5053 // Empty object at position 0 is ignored for invocation with `new`, but required. 5054 args.unshift(null); 5055 return new (Function.prototype.bind.apply(ctor, args))(); 5056 } 5057 5058 5059 return { 5060 invoke: invoke, 5061 instantiate: instantiate, 5062 get: getService, 5063 annotate: createInjector.$$annotate, 5064 has: function(name) { 5065 return providerCache.hasOwnProperty(name + providerSuffix) || cache.hasOwnProperty(name); 5066 } 5067 }; 5068 } 5069} 5070 5071createInjector.$$annotate = annotate; 5072 5073/** 5074 * @ngdoc provider 5075 * @name $anchorScrollProvider 5076 * @this 5077 * 5078 * @description 5079 * Use `$anchorScrollProvider` to disable automatic scrolling whenever 5080 * {@link ng.$location#hash $location.hash()} changes. 5081 */ 5082function $AnchorScrollProvider() { 5083 5084 var autoScrollingEnabled = true; 5085 5086 /** 5087 * @ngdoc method 5088 * @name $anchorScrollProvider#disableAutoScrolling 5089 * 5090 * @description 5091 * By default, {@link ng.$anchorScroll $anchorScroll()} will automatically detect changes to 5092 * {@link ng.$location#hash $location.hash()} and scroll to the element matching the new hash.<br /> 5093 * Use this method to disable automatic scrolling. 5094 * 5095 * If automatic scrolling is disabled, one must explicitly call 5096 * {@link ng.$anchorScroll $anchorScroll()} in order to scroll to the element related to the 5097 * current hash. 5098 */ 5099 this.disableAutoScrolling = function() { 5100 autoScrollingEnabled = false; 5101 }; 5102 5103 /** 5104 * @ngdoc service 5105 * @name $anchorScroll 5106 * @kind function 5107 * @requires $window 5108 * @requires $location 5109 * @requires $rootScope 5110 * 5111 * @description 5112 * When called, it scrolls to the element related to the specified `hash` or (if omitted) to the 5113 * current value of {@link ng.$location#hash $location.hash()}, according to the rules specified 5114 * in the 5115 * [HTML5 spec](http://www.w3.org/html/wg/drafts/html/master/browsers.html#an-indicated-part-of-the-document). 5116 * 5117 * It also watches the {@link ng.$location#hash $location.hash()} and automatically scrolls to 5118 * match any anchor whenever it changes. This can be disabled by calling 5119 * {@link ng.$anchorScrollProvider#disableAutoScrolling $anchorScrollProvider.disableAutoScrolling()}. 5120 * 5121 * Additionally, you can use its {@link ng.$anchorScroll#yOffset yOffset} property to specify a 5122 * vertical scroll-offset (either fixed or dynamic). 5123 * 5124 * @param {string=} hash The hash specifying the element to scroll to. If omitted, the value of 5125 * {@link ng.$location#hash $location.hash()} will be used. 5126 * 5127 * @property {(number|function|jqLite)} yOffset 5128 * If set, specifies a vertical scroll-offset. This is often useful when there are fixed 5129 * positioned elements at the top of the page, such as navbars, headers etc. 5130 * 5131 * `yOffset` can be specified in various ways: 5132 * - **number**: A fixed number of pixels to be used as offset.<br /><br /> 5133 * - **function**: A getter function called everytime `$anchorScroll()` is executed. Must return 5134 * a number representing the offset (in pixels).<br /><br /> 5135 * - **jqLite**: A jqLite/jQuery element to be used for specifying the offset. The distance from 5136 * the top of the page to the element's bottom will be used as offset.<br /> 5137 * **Note**: The element will be taken into account only as long as its `position` is set to 5138 * `fixed`. This option is useful, when dealing with responsive navbars/headers that adjust 5139 * their height and/or positioning according to the viewport's size. 5140 * 5141 * <br /> 5142 * <div class="alert alert-warning"> 5143 * In order for `yOffset` to work properly, scrolling should take place on the document's root and 5144 * not some child element. 5145 * </div> 5146 * 5147 * @example 5148 <example module="anchorScrollExample" name="anchor-scroll"> 5149 <file name="index.html"> 5150 <div id="scrollArea" ng-controller="ScrollController"> 5151 <a ng-click="gotoBottom()">Go to bottom</a> 5152 <a id="bottom"></a> You're at the bottom! 5153 </div> 5154 </file> 5155 <file name="script.js"> 5156 angular.module('anchorScrollExample', []) 5157 .controller('ScrollController', ['$scope', '$location', '$anchorScroll', 5158 function($scope, $location, $anchorScroll) { 5159 $scope.gotoBottom = function() { 5160 // set the location.hash to the id of 5161 // the element you wish to scroll to. 5162 $location.hash('bottom'); 5163 5164 // call $anchorScroll() 5165 $anchorScroll(); 5166 }; 5167 }]); 5168 </file> 5169 <file name="style.css"> 5170 #scrollArea { 5171 height: 280px; 5172 overflow: auto; 5173 } 5174 5175 #bottom { 5176 display: block; 5177 margin-top: 2000px; 5178 } 5179 </file> 5180 </example> 5181 * 5182 * <hr /> 5183 * The example below illustrates the use of a vertical scroll-offset (specified as a fixed value). 5184 * See {@link ng.$anchorScroll#yOffset $anchorScroll.yOffset} for more details. 5185 * 5186 * @example 5187 <example module="anchorScrollOffsetExample" name="anchor-scroll-offset"> 5188 <file name="index.html"> 5189 <div class="fixed-header" ng-controller="headerCtrl"> 5190 <a href="" ng-click="gotoAnchor(x)" ng-repeat="x in [1,2,3,4,5]"> 5191 Go to anchor {{x}} 5192 </a> 5193 </div> 5194 <div id="anchor{{x}}" class="anchor" ng-repeat="x in [1,2,3,4,5]"> 5195 Anchor {{x}} of 5 5196 </div> 5197 </file> 5198 <file name="script.js"> 5199 angular.module('anchorScrollOffsetExample', []) 5200 .run(['$anchorScroll', function($anchorScroll) { 5201 $anchorScroll.yOffset = 50; // always scroll by 50 extra pixels 5202 }]) 5203 .controller('headerCtrl', ['$anchorScroll', '$location', '$scope', 5204 function($anchorScroll, $location, $scope) { 5205 $scope.gotoAnchor = function(x) { 5206 var newHash = 'anchor' + x; 5207 if ($location.hash() !== newHash) { 5208 // set the $location.hash to `newHash` and 5209 // $anchorScroll will automatically scroll to it 5210 $location.hash('anchor' + x); 5211 } else { 5212 // call $anchorScroll() explicitly, 5213 // since $location.hash hasn't changed 5214 $anchorScroll(); 5215 } 5216 }; 5217 } 5218 ]); 5219 </file> 5220 <file name="style.css"> 5221 body { 5222 padding-top: 50px; 5223 } 5224 5225 .anchor { 5226 border: 2px dashed DarkOrchid; 5227 padding: 10px 10px 200px 10px; 5228 } 5229 5230 .fixed-header { 5231 background-color: rgba(0, 0, 0, 0.2); 5232 height: 50px; 5233 position: fixed; 5234 top: 0; left: 0; right: 0; 5235 } 5236 5237 .fixed-header > a { 5238 display: inline-block; 5239 margin: 5px 15px; 5240 } 5241 </file> 5242 </example> 5243 */ 5244 this.$get = ['$window', '$location', '$rootScope', function($window, $location, $rootScope) { 5245 var document = $window.document; 5246 5247 // Helper function to get first anchor from a NodeList 5248 // (using `Array#some()` instead of `angular#forEach()` since it's more performant 5249 // and working in all supported browsers.) 5250 function getFirstAnchor(list) { 5251 var result = null; 5252 Array.prototype.some.call(list, function(element) { 5253 if (nodeName_(element) === 'a') { 5254 result = element; 5255 return true; 5256 } 5257 }); 5258 return result; 5259 } 5260 5261 function getYOffset() { 5262 5263 var offset = scroll.yOffset; 5264 5265 if (isFunction(offset)) { 5266 offset = offset(); 5267 } else if (isElement(offset)) { 5268 var elem = offset[0]; 5269 var style = $window.getComputedStyle(elem); 5270 if (style.position !== 'fixed') { 5271 offset = 0; 5272 } else { 5273 offset = elem.getBoundingClientRect().bottom; 5274 } 5275 } else if (!isNumber(offset)) { 5276 offset = 0; 5277 } 5278 5279 return offset; 5280 } 5281 5282 function scrollTo(elem) { 5283 if (elem) { 5284 elem.scrollIntoView(); 5285 5286 var offset = getYOffset(); 5287 5288 if (offset) { 5289 // `offset` is the number of pixels we should scroll UP in order to align `elem` properly. 5290 // This is true ONLY if the call to `elem.scrollIntoView()` initially aligns `elem` at the 5291 // top of the viewport. 5292 // 5293 // IF the number of pixels from the top of `elem` to the end of the page's content is less 5294 // than the height of the viewport, then `elem.scrollIntoView()` will align the `elem` some 5295 // way down the page. 5296 // 5297 // This is often the case for elements near the bottom of the page. 5298 // 5299 // In such cases we do not need to scroll the whole `offset` up, just the difference between 5300 // the top of the element and the offset, which is enough to align the top of `elem` at the 5301 // desired position. 5302 var elemTop = elem.getBoundingClientRect().top; 5303 $window.scrollBy(0, elemTop - offset); 5304 } 5305 } else { 5306 $window.scrollTo(0, 0); 5307 } 5308 } 5309 5310 function scroll(hash) { 5311 // Allow numeric hashes 5312 hash = isString(hash) ? hash : isNumber(hash) ? hash.toString() : $location.hash(); 5313 var elm; 5314 5315 // empty hash, scroll to the top of the page 5316 if (!hash) scrollTo(null); 5317 5318 // element with given id 5319 else if ((elm = document.getElementById(hash))) scrollTo(elm); 5320 5321 // first anchor with given name :-D 5322 else if ((elm = getFirstAnchor(document.getElementsByName(hash)))) scrollTo(elm); 5323 5324 // no element and hash === 'top', scroll to the top of the page 5325 else if (hash === 'top') scrollTo(null); 5326 } 5327 5328 // does not scroll when user clicks on anchor link that is currently on 5329 // (no url change, no $location.hash() change), browser native does scroll 5330 if (autoScrollingEnabled) { 5331 $rootScope.$watch(function autoScrollWatch() {return $location.hash();}, 5332 function autoScrollWatchAction(newVal, oldVal) { 5333 // skip the initial scroll if $location.hash is empty 5334 if (newVal === oldVal && newVal === '') return; 5335 5336 jqLiteDocumentLoaded(function() { 5337 $rootScope.$evalAsync(scroll); 5338 }); 5339 }); 5340 } 5341 5342 return scroll; 5343 }]; 5344} 5345 5346var $animateMinErr = minErr('$animate'); 5347var ELEMENT_NODE = 1; 5348var NG_ANIMATE_CLASSNAME = 'ng-animate'; 5349 5350function mergeClasses(a,b) { 5351 if (!a && !b) return ''; 5352 if (!a) return b; 5353 if (!b) return a; 5354 if (isArray(a)) a = a.join(' '); 5355 if (isArray(b)) b = b.join(' '); 5356 return a + ' ' + b; 5357} 5358 5359function extractElementNode(element) { 5360 for (var i = 0; i < element.length; i++) { 5361 var elm = element[i]; 5362 if (elm.nodeType === ELEMENT_NODE) { 5363 return elm; 5364 } 5365 } 5366} 5367 5368function splitClasses(classes) { 5369 if (isString(classes)) { 5370 classes = classes.split(' '); 5371 } 5372 5373 // Use createMap() to prevent class assumptions involving property names in 5374 // Object.prototype 5375 var obj = createMap(); 5376 forEach(classes, function(klass) { 5377 // sometimes the split leaves empty string values 5378 // incase extra spaces were applied to the options 5379 if (klass.length) { 5380 obj[klass] = true; 5381 } 5382 }); 5383 return obj; 5384} 5385 5386// if any other type of options value besides an Object value is 5387// passed into the $animate.method() animation then this helper code 5388// will be run which will ignore it. While this patch is not the 5389// greatest solution to this, a lot of existing plugins depend on 5390// $animate to either call the callback (< 1.2) or return a promise 5391// that can be changed. This helper function ensures that the options 5392// are wiped clean incase a callback function is provided. 5393function prepareAnimateOptions(options) { 5394 return isObject(options) 5395 ? options 5396 : {}; 5397} 5398 5399var $$CoreAnimateJsProvider = /** @this */ function() { 5400 this.$get = noop; 5401}; 5402 5403// this is prefixed with Core since it conflicts with 5404// the animateQueueProvider defined in ngAnimate/animateQueue.js 5405var $$CoreAnimateQueueProvider = /** @this */ function() { 5406 var postDigestQueue = new NgMap(); 5407 var postDigestElements = []; 5408 5409 this.$get = ['$$AnimateRunner', '$rootScope', 5410 function($$AnimateRunner, $rootScope) { 5411 return { 5412 enabled: noop, 5413 on: noop, 5414 off: noop, 5415 pin: noop, 5416 5417 push: function(element, event, options, domOperation) { 5418 if (domOperation) { 5419 domOperation(); 5420 } 5421 5422 options = options || {}; 5423 if (options.from) { 5424 element.css(options.from); 5425 } 5426 if (options.to) { 5427 element.css(options.to); 5428 } 5429 5430 if (options.addClass || options.removeClass) { 5431 addRemoveClassesPostDigest(element, options.addClass, options.removeClass); 5432 } 5433 5434 var runner = new $$AnimateRunner(); 5435 5436 // since there are no animations to run the runner needs to be 5437 // notified that the animation call is complete. 5438 runner.complete(); 5439 return runner; 5440 } 5441 }; 5442 5443 5444 function updateData(data, classes, value) { 5445 var changed = false; 5446 if (classes) { 5447 classes = isString(classes) ? classes.split(' ') : 5448 isArray(classes) ? classes : []; 5449 forEach(classes, function(className) { 5450 if (className) { 5451 changed = true; 5452 data[className] = value; 5453 } 5454 }); 5455 } 5456 return changed; 5457 } 5458 5459 function handleCSSClassChanges() { 5460 forEach(postDigestElements, function(element) { 5461 var data = postDigestQueue.get(element); 5462 if (data) { 5463 var existing = splitClasses(element.attr('class')); 5464 var toAdd = ''; 5465 var toRemove = ''; 5466 forEach(data, function(status, className) { 5467 var hasClass = !!existing[className]; 5468 if (status !== hasClass) { 5469 if (status) { 5470 toAdd += (toAdd.length ? ' ' : '') + className; 5471 } else { 5472 toRemove += (toRemove.length ? ' ' : '') + className; 5473 } 5474 } 5475 }); 5476 5477 forEach(element, function(elm) { 5478 if (toAdd) { 5479 jqLiteAddClass(elm, toAdd); 5480 } 5481 if (toRemove) { 5482 jqLiteRemoveClass(elm, toRemove); 5483 } 5484 }); 5485 postDigestQueue.delete(element); 5486 } 5487 }); 5488 postDigestElements.length = 0; 5489 } 5490 5491 5492 function addRemoveClassesPostDigest(element, add, remove) { 5493 var data = postDigestQueue.get(element) || {}; 5494 5495 var classesAdded = updateData(data, add, true); 5496 var classesRemoved = updateData(data, remove, false); 5497 5498 if (classesAdded || classesRemoved) { 5499 5500 postDigestQueue.set(element, data); 5501 postDigestElements.push(element); 5502 5503 if (postDigestElements.length === 1) { 5504 $rootScope.$$postDigest(handleCSSClassChanges); 5505 } 5506 } 5507 } 5508 }]; 5509}; 5510 5511/** 5512 * @ngdoc provider 5513 * @name $animateProvider 5514 * 5515 * @description 5516 * Default implementation of $animate that doesn't perform any animations, instead just 5517 * synchronously performs DOM updates and resolves the returned runner promise. 5518 * 5519 * In order to enable animations the `ngAnimate` module has to be loaded. 5520 * 5521 * To see the functional implementation check out `src/ngAnimate/animate.js`. 5522 */ 5523var $AnimateProvider = ['$provide', /** @this */ function($provide) { 5524 var provider = this; 5525 var classNameFilter = null; 5526 var customFilter = null; 5527 5528 this.$$registeredAnimations = Object.create(null); 5529 5530 /** 5531 * @ngdoc method 5532 * @name $animateProvider#register 5533 * 5534 * @description 5535 * Registers a new injectable animation factory function. The factory function produces the 5536 * animation object which contains callback functions for each event that is expected to be 5537 * animated. 5538 * 5539 * * `eventFn`: `function(element, ... , doneFunction, options)` 5540 * The element to animate, the `doneFunction` and the options fed into the animation. Depending 5541 * on the type of animation additional arguments will be injected into the animation function. The 5542 * list below explains the function signatures for the different animation methods: 5543 * 5544 * - setClass: function(element, addedClasses, removedClasses, doneFunction, options) 5545 * - addClass: function(element, addedClasses, doneFunction, options) 5546 * - removeClass: function(element, removedClasses, doneFunction, options) 5547 * - enter, leave, move: function(element, doneFunction, options) 5548 * - animate: function(element, fromStyles, toStyles, doneFunction, options) 5549 * 5550 * Make sure to trigger the `doneFunction` once the animation is fully complete. 5551 * 5552 * ```js 5553 * return { 5554 * //enter, leave, move signature 5555 * eventFn : function(element, done, options) { 5556 * //code to run the animation 5557 * //once complete, then run done() 5558 * return function endFunction(wasCancelled) { 5559 * //code to cancel the animation 5560 * } 5561 * } 5562 * } 5563 * ``` 5564 * 5565 * @param {string} name The name of the animation (this is what the class-based CSS value will be compared to). 5566 * @param {Function} factory The factory function that will be executed to return the animation 5567 * object. 5568 */ 5569 this.register = function(name, factory) { 5570 if (name && name.charAt(0) !== '.') { 5571 throw $animateMinErr('notcsel', 'Expecting class selector starting with \'.\' got \'{0}\'.', name); 5572 } 5573 5574 var key = name + '-animation'; 5575 provider.$$registeredAnimations[name.substr(1)] = key; 5576 $provide.factory(key, factory); 5577 }; 5578 5579 /** 5580 * @ngdoc method 5581 * @name $animateProvider#customFilter 5582 * 5583 * @description 5584 * Sets and/or returns the custom filter function that is used to "filter" animations, i.e. 5585 * determine if an animation is allowed or not. When no filter is specified (the default), no 5586 * animation will be blocked. Setting the `customFilter` value will only allow animations for 5587 * which the filter function's return value is truthy. 5588 * 5589 * This allows to easily create arbitrarily complex rules for filtering animations, such as 5590 * allowing specific events only, or enabling animations on specific subtrees of the DOM, etc. 5591 * Filtering animations can also boost performance for low-powered devices, as well as 5592 * applications containing a lot of structural operations. 5593 * 5594 * <div class="alert alert-success"> 5595 * **Best Practice:** 5596 * Keep the filtering function as lean as possible, because it will be called for each DOM 5597 * action (e.g. insertion, removal, class change) performed by "animation-aware" directives. 5598 * See {@link guide/animations#which-directives-support-animations- here} for a list of built-in 5599 * directives that support animations. 5600 * Performing computationally expensive or time-consuming operations on each call of the 5601 * filtering function can make your animations sluggish. 5602 * </div> 5603 * 5604 * **Note:** If present, `customFilter` will be checked before 5605 * {@link $animateProvider#classNameFilter classNameFilter}. 5606 * 5607 * @param {Function=} filterFn - The filter function which will be used to filter all animations. 5608 * If a falsy value is returned, no animation will be performed. The function will be called 5609 * with the following arguments: 5610 * - **node** `{DOMElement}` - The DOM element to be animated. 5611 * - **event** `{String}` - The name of the animation event (e.g. `enter`, `leave`, `addClass` 5612 * etc). 5613 * - **options** `{Object}` - A collection of options/styles used for the animation. 5614 * @return {Function} The current filter function or `null` if there is none set. 5615 */ 5616 this.customFilter = function(filterFn) { 5617 if (arguments.length === 1) { 5618 customFilter = isFunction(filterFn) ? filterFn : null; 5619 } 5620 5621 return customFilter; 5622 }; 5623 5624 /** 5625 * @ngdoc method 5626 * @name $animateProvider#classNameFilter 5627 * 5628 * @description 5629 * Sets and/or returns the CSS class regular expression that is checked when performing 5630 * an animation. Upon bootstrap the classNameFilter value is not set at all and will 5631 * therefore enable $animate to attempt to perform an animation on any element that is triggered. 5632 * When setting the `classNameFilter` value, animations will only be performed on elements 5633 * that successfully match the filter expression. This in turn can boost performance 5634 * for low-powered devices as well as applications containing a lot of structural operations. 5635 * 5636 * **Note:** If present, `classNameFilter` will be checked after 5637 * {@link $animateProvider#customFilter customFilter}. If `customFilter` is present and returns 5638 * false, `classNameFilter` will not be checked. 5639 * 5640 * @param {RegExp=} expression The className expression which will be checked against all animations 5641 * @return {RegExp} The current CSS className expression value. If null then there is no expression value 5642 */ 5643 this.classNameFilter = function(expression) { 5644 if (arguments.length === 1) { 5645 classNameFilter = (expression instanceof RegExp) ? expression : null; 5646 if (classNameFilter) { 5647 var reservedRegex = new RegExp('[(\\s|\\/)]' + NG_ANIMATE_CLASSNAME + '[(\\s|\\/)]'); 5648 if (reservedRegex.test(classNameFilter.toString())) { 5649 classNameFilter = null; 5650 throw $animateMinErr('nongcls', '$animateProvider.classNameFilter(regex) prohibits accepting a regex value which matches/contains the "{0}" CSS class.', NG_ANIMATE_CLASSNAME); 5651 } 5652 } 5653 } 5654 return classNameFilter; 5655 }; 5656 5657 this.$get = ['$$animateQueue', function($$animateQueue) { 5658 function domInsert(element, parentElement, afterElement) { 5659 // if for some reason the previous element was removed 5660 // from the dom sometime before this code runs then let's 5661 // just stick to using the parent element as the anchor 5662 if (afterElement) { 5663 var afterNode = extractElementNode(afterElement); 5664 if (afterNode && !afterNode.parentNode && !afterNode.previousElementSibling) { 5665 afterElement = null; 5666 } 5667 } 5668 if (afterElement) { 5669 afterElement.after(element); 5670 } else { 5671 parentElement.prepend(element); 5672 } 5673 } 5674 5675 /** 5676 * @ngdoc service 5677 * @name $animate 5678 * @description The $animate service exposes a series of DOM utility methods that provide support 5679 * for animation hooks. The default behavior is the application of DOM operations, however, 5680 * when an animation is detected (and animations are enabled), $animate will do the heavy lifting 5681 * to ensure that animation runs with the triggered DOM operation. 5682 * 5683 * By default $animate doesn't trigger any animations. This is because the `ngAnimate` module isn't 5684 * included and only when it is active then the animation hooks that `$animate` triggers will be 5685 * functional. Once active then all structural `ng-` directives will trigger animations as they perform 5686 * their DOM-related operations (enter, leave and move). Other directives such as `ngClass`, 5687 * `ngShow`, `ngHide` and `ngMessages` also provide support for animations. 5688 * 5689 * It is recommended that the`$animate` service is always used when executing DOM-related procedures within directives. 5690 * 5691 * To learn more about enabling animation support, click here to visit the 5692 * {@link ngAnimate ngAnimate module page}. 5693 */ 5694 return { 5695 // we don't call it directly since non-existant arguments may 5696 // be interpreted as null within the sub enabled function 5697 5698 /** 5699 * 5700 * @ngdoc method 5701 * @name $animate#on 5702 * @kind function 5703 * @description Sets up an event listener to fire whenever the animation event (enter, leave, move, etc...) 5704 * has fired on the given element or among any of its children. Once the listener is fired, the provided callback 5705 * is fired with the following params: 5706 * 5707 * ```js 5708 * $animate.on('enter', container, 5709 * function callback(element, phase) { 5710 * // cool we detected an enter animation within the container 5711 * } 5712 * ); 5713 * ``` 5714 * 5715 *
5715@param {string} event the animation event that will be captured (e.g. enter, leave, move, addClass, removeClass, etc...) 5716 * @param {DOMElement} container the container element that will capture each of the animation events that are fired on itself 5717 * as well as among its children 5718 * @param {Function} callback the callback function that will be fired when the listener is triggered 5719 * 5720 * The arguments present in the callback function are: 5721 * * `element` - The captured DOM element that the animation was fired on. 5722 * * `phase` - The phase of the animation. The two possible phases are **start** (when the animation starts) and **close** (when it ends). 5723 */ 5724 on: $$animateQueue.on, 5725 5726 /** 5727 * 5728 * @ngdoc method 5729 * @name $animate#off 5730 * @kind function 5731 * @description Deregisters an event listener based on the event which has been associated with the provided element. This method 5732 * can be used in three different ways depending on the arguments: 5733 * 5734 * ```js 5735 * // remove all the animation event listeners listening for `enter` 5736 * $animate.off('enter'); 5737 * 5738 * // remove listeners for all animation events from the container element 5739 * $animate.off(container); 5740 * 5741 * // remove all the animation event listeners listening for `enter` on the given element and its children 5742 * $animate.off('enter', container); 5743 * 5744 * // remove the event listener function provided by `callback` that is set 5745 * // to listen for `enter` on the given `container` as well as its children 5746 * $animate.off('enter', container, callback); 5747 * ``` 5748 * 5749 * @param {string|DOMElement} event|container the animation event (e.g. enter, leave, move, 5750 * addClass, removeClass, etc...), or the container element. If it is the element, all other 5751 * arguments are ignored. 5752 * @param {DOMElement=} container the container element the event listener was placed on 5753 * @param {Function=} callback the callback function that was registered as the listener 5754 */ 5755 off: $$animateQueue.off, 5756 5757 /** 5758 * @ngdoc method 5759 * @name $animate#pin 5760 * @kind function 5761 * @description Associates the provided element with a host parent element to allow the element to be animated even if it exists 5762 * outside of the DOM structure of the Angular application. By doing so, any animation triggered via `$animate` can be issued on the 5763 * element despite being outside the realm of the application or within another application. Say for example if the application 5764 * was bootstrapped on an element that is somewhere inside of the `<body>` tag, but we wanted to allow for an element to be situated 5765 * as a direct child of `document.body`, then this can be achieved by pinning the element via `$animate.pin(element)`. Keep in mind 5766 * that calling `$animate.pin(element, parentElement)` will not actually insert into the DOM anywhere; it will just create the association. 5767 * 5768 * Note that this feature is only active when the `ngAnimate` module is used. 5769 * 5770 * @param {DOMElement} element the external element that will be pinned 5771 * @param {DOMElement} parentElement the host parent element that will be associated with the external element 5772 */ 5773 pin: $$animateQueue.pin, 5774 5775 /** 5776 * 5777 * @ngdoc method 5778 * @name $animate#enabled 5779 * @kind function 5780 * @description Used to get and set whether animations are enabled or not on the entire application or on an element and its children. This 5781 * function can be called in four ways: 5782 * 5783 * ```js 5784 * // returns true or false 5785 * $animate.enabled(); 5786 * 5787 * // changes the enabled state for all animations 5788 * $animate.enabled(false); 5789 * $animate.enabled(true); 5790 * 5791 * // returns true or false if animations are enabled for an element 5792 * $animate.enabled(element); 5793 * 5794 * // changes the enabled state for an element and its children 5795 * $animate.enabled(element, true); 5796 * $animate.enabled(element, false); 5797 * ``` 5798 * 5799 * @param {DOMElement=} element the element that will be considered for checking/setting the enabled state 5800 * @param {boolean=} enabled whether or not the animations will be enabled for the element 5801 * 5802 * @return {boolean} whether or not animations are enabled 5803 */ 5804 enabled: $$animateQueue.enabled, 5805 5806 /** 5807 * @ngdoc method 5808 * @name $animate#cancel 5809 * @kind function
5810 * @description Cancels the provided animation. 5811 * 5812 * @param {Promise} animationPromise The animation promise that is returned when an animation is started. 5813 */ 5814 cancel: function(runner) { 5815 if (runner.end) { 5816 runner.end(); 5817 } 5818 }, 5819 5820 /** 5821 * 5822 * @ngdoc method 5823 * @name $animate#enter 5824 * @kind function 5825 * @description Inserts the element into the DOM either after the `after` element (if provided) or 5826 * as the first child within the `parent` element and then triggers an animation. 5827 * A promise is returned that will be resolved during the next digest once the animation 5828 * has completed. 5829 * 5830 * @param {DOMElement} element the element which will be inserted into the DOM 5831 * @param {DOMElement} parent the parent element which will append the element as 5832 * a child (so long as the after element is not present) 5833 * @param {DOMElement=} after the sibling element after which the element will be appended 5834 * @param {object=} options an optional collection of options/styles that will be applied to the element. 5835 * The object can have the following properties: 5836 * 5837 * - **addClass** - `{string}` - space-separated CSS classes to add to element 5838 * - **from** - `{Object}` - CSS properties & values at the beginning of animation. Must have matching `to` 5839 * - **removeClass** - `{string}` - space-separated CSS classes to remove from element 5840 * - **to** - `{Object}` - CSS properties & values at end of animation. Must have matching `from` 5841 * 5842 * @return {Promise} the animation callback promise 5843 */ 5844 enter: function(element, parent, after, options) { 5845 parent = parent && jqLite(parent); 5846 after = after && jqLite(after); 5847 parent = parent || after.parent(); 5848 domInsert(element, parent, after); 5849 return $$animateQueue.push(element, 'enter', prepareAnimateOptions(options)); 5850 }, 5851 5852 /** 5853 * 5854 * @ngdoc method 5855 * @name $animate#move 5856 * @kind function 5857 * @description Inserts (moves) the element into its new position in the DOM either after 5858 * the `after` element (if provided) or as the first child within the `parent` element 5859 * and then triggers an animation. A promise is returned that will be resolved 5860 * during the next digest once the animation has completed. 5861 * 5862 * @param {DOMElement} element the element which will be moved into the new DOM position 5863 * @param {DOMElement} parent the parent element which will append the element as 5864 * a child (so long as the after element is not present) 5865 * @param {DOMElement=} after the sibling element after which the element will be appended 5866 * @param {object=} options an optional collection of options/styles that will be applied to the element. 5867 * The object can have the following properties: 5868 * 5869 * - **addClass** - `{string}` - space-separated CSS classes to add to element 5870 * - **from** - `{Object}` - CSS properties & values at the beginning of animation. Must have matching `to` 5871 * - **removeClass** - `{string}` - space-separated CSS classes to remove from element 5872 * - **to** - `{Object}` - CSS properties & values at end of animation. Must have matching `from` 5873 * 5874 * @return {Promise} the animation callback promise 5875 */ 5876 move: function(element, parent, after, options) { 5877 parent = parent && jqLite(parent); 5878 after = after && jqLite(after); 5879 parent = parent || after.parent(); 5880 domInsert(element, parent, after); 5881 return $$animateQueue.push(element, 'move', prepareAnimateOptions(options)); 5882 }, 5883 5884 /** 5885 * @ngdoc method 5886 * @name $animate#leave 5887 * @kind function 5888 * @description Triggers an animation and then removes the element from the DOM. 5889 * When the function is called a promise is returned that will be resolved during the next 5890 * digest once the animation has completed. 5891 * 5892 * @param {DOMElement} element the element which will be removed from the DOM 5893 * @param {object=} options an optional collection of options/styles that will be applied to the element. 5894 * The object can have the following properties: 5895 * 5896 * - **addClass** - `{string}` - space-separated CSS classes to add to element 5897 * - **from** - `{Object}` - CSS properties & values at the beginning of animation. Must have matching `to` 5898 * - **removeClass** - `{string}` - space-separated CSS classes to remove from element 5899 * - **to** - `{Object}` - CSS properties & values at end of animation. Must have matching `from` 5900 * 5901 * @return {Promise} the animation callback promise 5902 */ 5903 leave: function(element, options) { 5904 return $$animateQueue.push(element, 'leave', prepareAnimateOptions(options), function() { 5905 element.remove(); 5906 }); 5907 }, 5908 5909 /** 5910 * @ngdoc method 5911 * @name $animate#addClass 5912 * @kind function 5913 *
5914 * @description Triggers an addClass animation surrounding the addition of the provided CSS class(es). Upon 5915 * execution, the addClass operation will only be handled after the next digest and it will not trigger an 5916 * animation if element already contains the CSS class or if the class is removed at a later step. 5917 * Note that class-based animations are treated differently compared to structural animations 5918 * (like enter, move and leave) since the CSS classes may be added/removed at different points 5919 * depending if CSS or JavaScript animations are used. 5920 * 5921 * @param {DOMElement} element the element which the CSS classes will be applied to 5922 * @param {string} className the CSS class(es) that will be added (multiple classes are separated via spaces) 5923 * @param {object=} options an optional collection of options/styles that will be applied to the element. 5924 * The object can have the following properties: 5925 * 5926 * - **addClass** - `{string}` - space-separated CSS classes to add to element 5927 * - **from** - `{Object}` - CSS properties & values at the beginning of animation. Must have matching `to` 5928 * - **removeClass** - `{string}` - space-separated CSS classes to remove from element 5929 * - **to** - `{Object}` - CSS properties & values at end of animation. Must have matching `from` 5930 * 5931 * @return {Promise} the animation callback promise 5932 */ 5933 addClass: function(element, className, options) { 5934 options = prepareAnimateOptions(options); 5935 options.addClass = mergeClasses(options.addclass, className); 5936 return $$animateQueue.push(element, 'addClass', options); 5937 }, 5938 5939 /** 5940 * @ngdoc method 5941 * @name $animate#removeClass 5942 * @kind function 5943 * 5944 * @description Triggers a removeClass animation surrounding the removal of the provided CSS class(es). Upon 5945 * execution, the removeClass operation will only be handled after the next digest and it will not trigger an 5946 * animation if element does not contain the CSS class or if the class is added at a later step. 5947 * Note that class-based animations are treated differently compared to structural animations 5948 * (like enter, move and leave) since the CSS classes may be added/removed at different points 5949 * depending if CSS or JavaScript animations are used. 5950 * 5951 * @param {DOMElement} element the element which the CSS classes will be applied to 5952 * @param {string} className the CSS class(es) that will be removed (multiple classes are separated via spaces) 5953 * @param {object=} options an optional collection of options/styles that will be applied to the element. 5954 * The object can have the following properties: 5955 * 5956 * - **addClass** - `{string}` - space-separated CSS classes to add to element 5957 * - **from** - `{Object}` - CSS properties & values at the beginning of animation. Must have matching `to` 5958 * - **removeClass** - `{string}` - space-separated CSS classes to remove from element 5959 * - **to** - `{Object}` - CSS properties & values at end of animation. Must have matching `from` 5960 * 5961 * @return {Promise} the animation callback promise 5962 */ 5963 removeClass: function(element, className, options) { 5964 options = prepareAnimateOptions(options); 5965 options.removeClass = mergeClasses(options.removeClass, className); 5966 return $$animateQueue.push(element, 'removeClass', options); 5967 }, 5968 5969 /** 5970 * @ngdoc method 5971 * @name $animate#setClass 5972 * @kind function 5973 * 5974 * @description Performs both the addition and removal of a CSS classes on an element and (during the process) 5975 * triggers an animation surrounding the class addition/removal. Much like `$animate.addClass` and 5976 * `$animate.removeClass`, `setClass` will only evaluate the classes being added/removed once a digest has 5977 * passed. Note that class-based animations are treated differently compared to structural animations 5978 * (like enter, move and leave) since the CSS classes may be added/removed at different points 5979 * depending if CSS or JavaScript animations are used. 5980 * 5981 * @param {DOMElement} element the element which the CSS classes will be applied to 5982 * @param {string} add the CSS class(es) that will be added (multiple classes are separated via spaces) 5983 * @param {string} remove the CSS class(es) that will be removed (multiple classes are separated via spaces) 5984 * @param {object=} options an optional collection of options/styles that will be applied to the element. 5985 * The object can have the following properties: 5986 * 5987 * - **addClass** - `{string}` - space-separated CSS classes to add to element 5988 * - **from** - `{Object}` - CSS properties & values at the beginning of animation. Must have matching `to` 5989 * - **removeClass** - `{string}` - space-separated CSS classes to remove from element 5990 * - **to** - `{Object}` - CSS properties & values at end of animation. Must have matching `from` 5991 * 5992 * @return {Promise} the animation callback promise 5993 */ 5994 setClass: function(element, add, remove, options) { 5995 options = prepareAnimateOptions(options); 5996 options.addClass = mergeClasses(options.addClass, add); 5997 options.removeClass = mergeClasses(options.removeClass, remove); 5998 return $$animateQueue.push(element, 'setClass', options); 5999 }, 6000 6001 /** 6002 * @ngdoc method 6003 * @name $animate#animate 6004 * @kind function 6005 *
6006 * @description Performs an inline animation on the element which applies the provided to and from CSS styles to the element. 6007 * If any detected CSS transition, keyframe or JavaScript matches the provided className value, then the animation will take 6008 * on the provided styles. For example, if a transition animation is set for the given className, then the provided `from` and 6009 * `to` styles will be applied alongside the given transition. If the CSS style provided in `from` does not have a corresponding 6010 * style in `to`, the style in `from` is applied immediately, and no animation is run. 6011 * If a JavaScript animation is detected then the provided styles will be given in as function parameters into the `animate` 6012 * method (or as part of the `options` parameter): 6013 * 6014 * ```js 6015 * ngModule.animation('.my-inline-animation', function() { 6016 * return { 6017 * animate : function(element, from, to, done, options) { 6018 * //animation 6019 * done(); 6020 * } 6021 * } 6022 * }); 6023 * ``` 6024 * 6025 * @param {DOMElement} element the element which the CSS styles will be applied to 6026 * @param {object} from the from (starting) CSS styles that will be applied to the element and across the animation. 6027 * @param {object} to the to (destination) CSS styles that will be applied to the element and across the animation. 6028 * @param {string=} className an optional CSS class that will be applied to the element for the duration of the animation. If 6029 * this value is left as empty then a CSS class of `ng-inline-animate` will be applied to the element. 6030 * (Note that if no animation is detected then this value will not be applied to the element.) 6031 * @param {object=} options an optional collection of options/styles that will be applied to the element. 6032 * The object can have the following properties: 6033 * 6034 * - **addClass** - `{string}` - space-separated CSS classes to add to element 6035 * - **from** - `{Object}` - CSS properties & values at the beginning of animation. Must have matching `to` 6036 * - **removeClass** - `{string}` - space-separated CSS classes to remove from element 6037 * - **to** - `{Object}` - CSS properties & values at end of animation. Must have matching `from` 6038 * 6039 * @return {Promise} the animation callback promise 6040 */ 6041 animate: function(element, from, to, className, options) { 6042 options = prepareAnimateOptions(options); 6043 options.from = options.from ? extend(options.from, from) : from; 6044 options.to = options.to ? extend(options.to, to) : to; 6045 6046 className = className || 'ng-inline-animate';
vendor: 29,853 bytes, lines 6047-7076
6047 options.tempClasses = mergeClasses(options.tempClasses, className); 6048 return $$animateQueue.push(element, 'animate', options); 6049 } 6050 }; 6051 }]; 6052}]; 6053 6054var $$AnimateAsyncRunFactoryProvider = /** @this */ function() { 6055 this.$get = ['$$rAF', function($$rAF) { 6056 var waitQueue = []; 6057 6058 function waitForTick(fn) { 6059 waitQueue.push(fn); 6060 if (waitQueue.length > 1) return; 6061 $$rAF(function() { 6062 for (var i = 0; i < waitQueue.length; i++) { 6063 waitQueue[i](); 6064 } 6065 waitQueue = []; 6066 }); 6067 } 6068 6069 return function() { 6070 var passed = false; 6071 waitForTick(function() { 6072 passed = true; 6073 }); 6074 return function(callback) { 6075 if (passed) { 6076 callback(); 6077 } else { 6078 waitForTick(callback); 6079 } 6080 }; 6081 }; 6082 }]; 6083}; 6084 6085var $$AnimateRunnerFactoryProvider = /** @this */ function() { 6086 this.$get = ['$q', '$sniffer', '$$animateAsyncRun', '$$isDocumentHidden', '$timeout', 6087 function($q, $sniffer, $$animateAsyncRun, $$isDocumentHidden, $timeout) { 6088 6089 var INITIAL_STATE = 0; 6090 var DONE_PENDING_STATE = 1; 6091 var DONE_COMPLETE_STATE = 2; 6092 6093 AnimateRunner.chain = function(chain, callback) { 6094 var index = 0; 6095 6096 next(); 6097 function next() { 6098 if (index === chain.length) { 6099 callback(true); 6100 return; 6101 } 6102 6103 chain[index](function(response) { 6104 if (response === false) { 6105 callback(false); 6106 return; 6107 } 6108 index++; 6109 next(); 6110 }); 6111 } 6112 }; 6113 6114 AnimateRunner.all = function(runners, callback) { 6115 var count = 0; 6116 var status = true; 6117 forEach(runners, function(runner) { 6118 runner.done(onProgress); 6119 }); 6120 6121 function onProgress(response) { 6122 status = status && response; 6123 if (++count === runners.length) { 6124 callback(status); 6125 } 6126 } 6127 }; 6128 6129 function AnimateRunner(host) { 6130 this.setHost(host); 6131 6132 var rafTick = $$animateAsyncRun(); 6133 var timeoutTick = function(fn) { 6134 $timeout(fn, 0, false); 6135 }; 6136 6137 this._doneCallbacks = []; 6138 this._tick = function(fn) { 6139 if ($$isDocumentHidden()) { 6140 timeoutTick(fn); 6141 } else { 6142 rafTick(fn); 6143 } 6144 }; 6145 this._state = 0; 6146 } 6147 6148 AnimateRunner.prototype = { 6149 setHost: function(host) { 6150 this.host = host || {}; 6151 }, 6152 6153 done: function(fn) { 6154 if (this._state === DONE_COMPLETE_STATE) { 6155 fn(); 6156 } else { 6157 this._doneCallbacks.push(fn); 6158 } 6159 }, 6160 6161 progress: noop, 6162 6163 getPromise: function() { 6164 if (!this.promise) { 6165 var self = this; 6166 this.promise = $q(function(resolve, reject) { 6167 self.done(function(status) { 6168 if (status === false) { 6169 reject(); 6170 } else { 6171 resolve(); 6172 } 6173 }); 6174 }); 6175 } 6176 return this.promise; 6177 }, 6178 6179 then: function(resolveHandler, rejectHandler) { 6180 return this.getPromise().then(resolveHandler, rejectHandler); 6181 }, 6182 6183 'catch': function(handler) { 6184 return this.getPromise()['catch'](handler); 6185 }, 6186 6187 'finally': function(handler) { 6188 return this.getPromise()['finally'](handler); 6189 }, 6190 6191 pause: function() { 6192 if (this.host.pause) { 6193 this.host.pause(); 6194 } 6195 }, 6196 6197 resume: function() { 6198 if (this.host.resume) { 6199 this.host.resume(); 6200 } 6201 }, 6202 6203 end: function() { 6204 if (this.host.end) { 6205 this.host.end(); 6206 } 6207 this._resolve(true); 6208 }, 6209 6210 cancel: function() { 6211 if (this.host.cancel) { 6212 this.host.cancel(); 6213 } 6214 this._resolve(false); 6215 }, 6216 6217 complete: function(response) { 6218 var self = this; 6219 if (self._state === INITIAL_STATE) { 6220 self._state = DONE_PENDING_STATE; 6221 self._tick(function() { 6222 self._resolve(response); 6223 }); 6224 } 6225 }, 6226 6227 _resolve: function(response) { 6228 if (this._state !== DONE_COMPLETE_STATE) { 6229 forEach(this._doneCallbacks, function(fn) { 6230 fn(response); 6231 }); 6232 this._doneCallbacks.length = 0; 6233 this._state = DONE_COMPLETE_STATE; 6234 } 6235 } 6236 }; 6237 6238 return AnimateRunner; 6239 }]; 6240}; 6241 6242/* exported $CoreAnimateCssProvider */ 6243 6244/** 6245 * @ngdoc service 6246 * @name $animateCss 6247 * @kind object 6248 * @this 6249 * 6250 * @description 6251 * This is the core version of `$animateCss`. By default, only when the `ngAnimate` is included, 6252 * then the `$animateCss` service will actually perform animations. 6253 * 6254 * Click here {@link ngAnimate.$animateCss to read the documentation for $animateCss}. 6255 */ 6256var $CoreAnimateCssProvider = function() { 6257 this.$get = ['$$rAF', '$q', '$$AnimateRunner', function($$rAF, $q, $$AnimateRunner) { 6258 6259 return function(element, initialOptions) { 6260 // all of the animation functions should create 6261 // a copy of the options data, however, if a 6262 // parent service has already created a copy then 6263 // we should stick to using that 6264 var options = initialOptions || {}; 6265 if (!options.$$prepared) { 6266 options = copy(options); 6267 } 6268 6269 // there is no point in applying the styles since 6270 // there is no animation that goes on at all in 6271 // this version of $animateCss. 6272 if (options.cleanupStyles) { 6273 options.from = options.to = null; 6274 } 6275 6276 if (options.from) { 6277 element.css(options.from); 6278 options.from = null; 6279 } 6280 6281 var closed, runner = new $$AnimateRunner(); 6282 return { 6283 start: run, 6284 end: run 6285 }; 6286 6287 function run() { 6288 $$rAF(function() { 6289 applyAnimationContents(); 6290 if (!closed) { 6291 runner.complete(); 6292 } 6293 closed = true; 6294 }); 6295 return runner; 6296 } 6297 6298 function applyAnimationContents() { 6299 if (options.addClass) { 6300 element.addClass(options.addClass); 6301 options.addClass = null; 6302 } 6303 if (options.removeClass) { 6304 element.removeClass(options.removeClass); 6305 options.removeClass = null; 6306 } 6307 if (options.to) { 6308 element.css(options.to); 6309 options.to = null; 6310 } 6311 } 6312 }; 6313 }]; 6314}; 6315 6316/* global stripHash: true */ 6317 6318/** 6319 * ! This is a private undocumented service ! 6320 * 6321 * @name $browser 6322 * @requires $log 6323 * @description 6324 * This object has two goals: 6325 * 6326 * - hide all the global state in the browser caused by the window object 6327 * - abstract away all the browser specific features and inconsistencies 6328 * 6329 * For tests we provide {@link ngMock.$browser mock implementation} of the `$browser` 6330 * service, which can be used for convenient testing of the application without the interaction with 6331 * the real browser apis. 6332 */ 6333/** 6334 * @param {object} window The global window object. 6335 * @param {object} document jQuery wrapped document. 6336 * @param {object} $log window.console or an object with the same interface. 6337 * @param {object} $sniffer $sniffer service 6338 */ 6339function Browser(window, document, $log, $sniffer) { 6340 var self = this, 6341 location = window.location, 6342 history = window.history, 6343 setTimeout = window.setTimeout, 6344 clearTimeout = window.clearTimeout, 6345 pendingDeferIds = {}; 6346 6347 self.isMock = false; 6348 6349 var outstandingRequestCount = 0; 6350 var outstandingRequestCallbacks = []; 6351 6352 // TODO(vojta): remove this temporary api 6353 self.$$completeOutstandingRequest = completeOutstandingRequest; 6354 self.$$incOutstandingRequestCount = function() { outstandingRequestCount++; }; 6355 6356 /** 6357 * Executes the `fn` function(supports currying) and decrements the `outstandingRequestCallbacks` 6358 * counter. If the counter reaches 0, all the `outstandingRequestCallbacks` are executed. 6359 */ 6360 function completeOutstandingRequest(fn) { 6361 try { 6362 fn.apply(null, sliceArgs(arguments, 1)); 6363 } finally { 6364 outstandingRequestCount--; 6365 if (outstandingRequestCount === 0) { 6366 while (outstandingRequestCallbacks.length) { 6367 try { 6368 outstandingRequestCallbacks.pop()(); 6369 } catch (e) { 6370 $log.error(e); 6371 } 6372 } 6373 } 6374 } 6375 } 6376 6377 function getHash(url) { 6378 var index = url.indexOf('#'); 6379 return index === -1 ? '' : url.substr(index); 6380 } 6381 6382 /** 6383 * @private 6384 * Note: this method is used only by scenario runner 6385 * TODO(vojta): prefix this method with $$ ? 6386 * @param {function()} callback Function that will be called when no outstanding request 6387 */ 6388 self.notifyWhenNoOutstandingRequests = function(callback) { 6389 if (outstandingRequestCount === 0) { 6390 callback(); 6391 } else { 6392 outstandingRequestCallbacks.push(callback); 6393 } 6394 }; 6395 6396 ////////////////////////////////////////////////////////////// 6397 // URL API 6398 ////////////////////////////////////////////////////////////// 6399 6400 var cachedState, lastHistoryState, 6401 lastBrowserUrl = location.href, 6402 baseElement = document.find('base'), 6403 pendingLocation = null, 6404 getCurrentState = !$sniffer.history ? noop : function getCurrentState() { 6405 try { 6406 return history.state; 6407 } catch (e) { 6408 // MSIE can reportedly throw when there is no state (UNCONFIRMED). 6409 } 6410 }; 6411 6412 cacheState(); 6413 6414 /** 6415 * @name $browser#url 6416 * 6417 * @description 6418 * GETTER: 6419 * Without any argument, this method just returns current value of location.href. 6420 * 6421 * SETTER: 6422 * With at least one argument, this method sets url to new value. 6423 * If html5 history api supported, pushState/replaceState is used, otherwise 6424 * location.href/location.replace is used. 6425 * Returns its own instance to allow chaining 6426 * 6427 * NOTE: this api is intended for use only by the $location service. Please use the 6428 * {@link ng.$location $location service} to change url. 6429 * 6430 * @param {string} url New url (when used as setter) 6431 * @param {boolean=} replace Should new url replace current history record? 6432 * @param {object=} state object to use with pushState/replaceState 6433 */ 6434 self.url = function(url, replace, state) { 6435 // In modern browsers `history.state` is `null` by default; treating it separately 6436 // from `undefined` would cause `$browser.url('/foo')` to change `history.state` 6437 // to undefined via `pushState`. Instead, let's change `undefined` to `null` here. 6438 if (isUndefined(state)) { 6439 state = null; 6440 } 6441 6442 // Android Browser BFCache causes location, history reference to become stale. 6443 if (location !== window.location) location = window.location; 6444 if (history !== window.history) history = window.history; 6445 6446 // setter 6447 if (url) { 6448 var sameState = lastHistoryState === state; 6449 6450 // Don't change anything if previous and current URLs and states match. This also prevents 6451 // IE<10 from getting into redirect loop when in LocationHashbangInHtml5Url mode. 6452 // See https://github.com/angular/angular.js/commit/ffb2701 6453 if (lastBrowserUrl === url && (!$sniffer.history || sameState)) { 6454 return self; 6455 } 6456 var sameBase = lastBrowserUrl && stripHash(lastBrowserUrl) === stripHash(url); 6457 lastBrowserUrl = url; 6458 lastHistoryState = state; 6459 // Don't use history API if only the hash changed 6460 // due to a bug in IE10/IE11 which leads 6461 // to not firing a `hashchange` nor `popstate` event 6462 // in some cases (see #9143). 6463 if ($sniffer.history && (!sameBase || !sameState)) { 6464 history[replace ? 'replaceState' : 'pushState'](state, '', url); 6465 cacheState(); 6466 } else { 6467 if (!sameBase) { 6468 pendingLocation = url; 6469 } 6470 if (replace) { 6471 location.replace(url); 6472 } else if (!sameBase) { 6473 location.href = url; 6474 } else { 6475 location.hash = getHash(url); 6476 } 6477 if (location.href !== url) { 6478 pendingLocation = url; 6479 } 6480 } 6481 if (pendingLocation) { 6482 pendingLocation = url; 6483 } 6484 return self; 6485 // getter 6486 } else { 6487 // - pendingLocation is needed as browsers don't allow to read out 6488 // the new location.href if a reload happened or if there is a bug like in iOS 9 (see 6489 // https://openradar.appspot.com/22186109). 6490 // - the replacement is a workaround for https://bugzilla.mozilla.org/show_bug.cgi?id=407172 6491 return pendingLocation || location.href.replace(/%27/g,'\''); 6492 } 6493 }; 6494 6495 /** 6496 * @name $browser#state 6497 * 6498 * @description 6499 * This method is a getter. 6500 * 6501 * Return history.state or null if history.state is undefined. 6502 * 6503 * @returns {object} state 6504 */ 6505 self.state = function() { 6506 return cachedState; 6507 }; 6508 6509 var urlChangeListeners = [], 6510 urlChangeInit = false; 6511 6512 function cacheStateAndFireUrlChange() { 6513 pendingLocation = null; 6514 fireStateOrUrlChange(); 6515 } 6516 6517 // This variable should be used *only* inside the cacheState function. 6518 var lastCachedState = null; 6519 function cacheState() { 6520 // This should be the only place in $browser where `history.state` is read. 6521 cachedState = getCurrentState(); 6522 cachedState = isUndefined(cachedState) ? null : cachedState; 6523 6524 // Prevent callbacks fo fire twice if both hashchange & popstate were fired. 6525 if (equals(cachedState, lastCachedState)) { 6526 cachedState = lastCachedState; 6527 } 6528 6529 lastCachedState = cachedState; 6530 lastHistoryState = cachedState; 6531 } 6532 6533 function fireStateOrUrlChange() { 6534 var prevLastHistoryState = lastHistoryState; 6535 cacheState(); 6536 6537 if (lastBrowserUrl === self.url() && prevLastHistoryState === cachedState) { 6538 return; 6539 } 6540 6541 lastBrowserUrl = self.url(); 6542 lastHistoryState = cachedState; 6543 forEach(urlChangeListeners, function(listener) { 6544 listener(self.url(), cachedState); 6545 }); 6546 } 6547 6548 /** 6549 * @name $browser#onUrlChange 6550 * 6551 * @description 6552 * Register callback function that will be called, when url changes. 6553 * 6554 * It's only called when the url is changed from outside of angular: 6555 * - user types different url into address bar 6556 * - user clicks on history (forward/back) button 6557 * - user clicks on a link 6558 * 6559 * It's not called when url is changed by $browser.url() method 6560 * 6561 * The listener gets called with new url as parameter. 6562 * 6563 * NOTE: this api is intended for use only by the $location service. Please use the 6564 * {@link ng.$location $location service} to monitor url changes in angular apps. 6565 * 6566 * @param {function(string)} listener Listener function to be called when url changes. 6567 * @return {function(string)} Returns the registered listener fn - handy if the fn is anonymous. 6568 */ 6569 self.onUrlChange = function(callback) { 6570 // TODO(vojta): refactor to use node's syntax for events 6571 if (!urlChangeInit) { 6572 // We listen on both (hashchange/popstate) when available, as some browsers don't 6573 // fire popstate when user changes the address bar and don't fire hashchange when url 6574 // changed by push/replaceState 6575 6576 // html5 history api - popstate event 6577 if ($sniffer.history) jqLite(window).on('popstate', cacheStateAndFireUrlChange); 6578 // hashchange event 6579 jqLite(window).on('hashchange', cacheStateAndFireUrlChange); 6580 6581 urlChangeInit = true; 6582 } 6583 6584 urlChangeListeners.push(callback); 6585 return callback; 6586 }; 6587 6588 /** 6589 * @private 6590 * Remove popstate and hashchange handler from window. 6591 * 6592 * NOTE: this api is intended for use only by $rootScope. 6593 */ 6594 self.$$applicationDestroyed = function() { 6595 jqLite(window).off('hashchange popstate', cacheStateAndFireUrlChange); 6596 }; 6597 6598 /** 6599 * Checks whether the url has changed outside of Angular. 6600 * Needs to be exported to be able to check for changes that have been done in sync, 6601 * as hashchange/popstate events fire in async. 6602 */ 6603 self.$$checkUrlChange = fireStateOrUrlChange; 6604 6605 ////////////////////////////////////////////////////////////// 6606 // Misc API 6607 ////////////////////////////////////////////////////////////// 6608 6609 /** 6610 * @name $browser#baseHref 6611 * 6612 * @description 6613 * Returns current <base href> 6614 * (always relative - without domain) 6615 * 6616 * @returns {string} The current base href 6617 */ 6618 self.baseHref = function() { 6619 var href = baseElement.attr('href'); 6620 return href ? href.replace(/^(https?:)?\/\/[^/]*/, '') : ''; 6621 }; 6622 6623 /** 6624 * @name $browser#defer 6625 * @param {function()} fn A function, who's execution should be deferred. 6626 * @param {number=} [delay=0] of milliseconds to defer the function execution. 6627 * @returns {*} DeferId that can be used to cancel the task via `$browser.defer.cancel()`. 6628 * 6629 * @description 6630 * Executes a fn asynchronously via `setTimeout(fn, delay)`. 6631 * 6632 * Unlike when calling `setTimeout` directly, in test this function is mocked and instead of using 6633 * `setTimeout` in tests, the fns are queued in an array, which can be programmatically flushed 6634 * via `$browser.defer.flush()`. 6635 * 6636 */ 6637 self.defer = function(fn, delay) { 6638 var timeoutId; 6639 outstandingRequestCount++; 6640 timeoutId = setTimeout(function() { 6641 delete pendingDeferIds[timeoutId]; 6642 completeOutstandingRequest(fn); 6643 }, delay || 0); 6644 pendingDeferIds[timeoutId] = true; 6645 return timeoutId; 6646 }; 6647 6648 6649 /** 6650 * @name $browser#defer.cancel 6651 * 6652 * @description 6653 * Cancels a deferred task identified with `deferId`. 6654 * 6655 * @param {*} deferId Token returned by the `$browser.defer` function. 6656 * @returns {boolean} Returns `true` if the task hasn't executed yet and was successfully 6657 * canceled. 6658 */ 6659 self.defer.cancel = function(deferId) { 6660 if (pendingDeferIds[deferId]) { 6661 delete pendingDeferIds[deferId]; 6662 clearTimeout(deferId); 6663 completeOutstandingRequest(noop); 6664 return true; 6665 } 6666 return false; 6667 }; 6668 6669} 6670 6671/** @this */ 6672function $BrowserProvider() { 6673 this.$get = ['$window', '$log', '$sniffer', '$document', 6674 function($window, $log, $sniffer, $document) { 6675 return new Browser($window, $document, $log, $sniffer); 6676 }]; 6677} 6678 6679/** 6680 * @ngdoc service 6681 * @name $cacheFactory 6682 * @this 6683 * 6684 * @description 6685 * Factory that constructs {@link $cacheFactory.Cache Cache} objects and gives access to 6686 * them. 6687 * 6688 * ```js 6689 * 6690 * var cache = $cacheFactory('cacheId'); 6691 * expect($cacheFactory.get('cacheId')).toBe(cache); 6692 * expect($cacheFactory.get('noSuchCacheId')).not.toBeDefined(); 6693 * 6694 * cache.put("key", "value"); 6695 * cache.put("another key", "another value"); 6696 * 6697 * // We've specified no options on creation 6698 * expect(cache.info()).toEqual({id: 'cacheId', size: 2}); 6699 * 6700 * ``` 6701 * 6702 * 6703 * @param {string} cacheId Name or id of the newly created cache. 6704 * @param {object=} options Options object that specifies the cache behavior. Properties: 6705 * 6706 * - `{number=}` `capacity` — turns the cache into LRU cache. 6707 * 6708 * @returns {object} Newly created cache object with the following set of methods: 6709 * 6710 * - `{object}` `info()` — Returns id, size, and options of cache. 6711 * - `{{*}}` `put({string} key, {*} value)` — Puts a new key-value pair into the cache and returns 6712 * it. 6713 * - `{{*}}` `get({string} key)` — Returns cached value for `key` or undefined for cache miss. 6714 * - `{void}` `remove({string} key)` — Removes a key-value pair from the cache. 6715 * - `{void}` `removeAll()` — Removes all cached values. 6716 * - `{void}` `destroy()` — Removes references to this cache from $cacheFactory. 6717 * 6718 * @example 6719 <example module="cacheExampleApp" name="cache-factory"> 6720 <file name="index.html"> 6721 <div ng-controller="CacheController"> 6722 <input ng-model="newCacheKey" placeholder="Key"> 6723 <input ng-model="newCacheValue" placeholder="Value"> 6724 <button ng-click="put(newCacheKey, newCacheValue)">Cache</button> 6725 6726 <p ng-if="keys.length">Cached Values</p> 6727 <div ng-repeat="key in keys"> 6728 <span ng-bind="key"></span> 6729 <span>: </span> 6730 <b ng-bind="cache.get(key)"></b> 6731 </div> 6732 6733 <p>Cache Info</p> 6734 <div ng-repeat="(key, value) in cache.info()"> 6735 <span ng-bind="key"></span> 6736 <span>: </span> 6737 <b ng-bind="value"></b> 6738 </div> 6739 </div> 6740 </file> 6741 <file name="script.js"> 6742 angular.module('cacheExampleApp', []). 6743 controller('CacheController', ['$scope', '$cacheFactory', function($scope, $cacheFactory) { 6744 $scope.keys = []; 6745 $scope.cache = $cacheFactory('cacheId'); 6746 $scope.put = function(key, value) { 6747 if (angular.isUndefined($scope.cache.get(key))) { 6748 $scope.keys.push(key); 6749 } 6750 $scope.cache.put(key, angular.isUndefined(value) ? null : value); 6751 }; 6752 }]); 6753 </file> 6754 <file name="style.css"> 6755 p { 6756 margin: 10px 0 3px; 6757 } 6758 </file> 6759 </example> 6760 */ 6761function $CacheFactoryProvider() { 6762 6763 this.$get = function() { 6764 var caches = {}; 6765 6766 function cacheFactory(cacheId, options) { 6767 if (cacheId in caches) { 6768 throw minErr('$cacheFactory')('iid', 'CacheId \'{0}\' is already taken!', cacheId); 6769 } 6770 6771 var size = 0, 6772 stats = extend({}, options, {id: cacheId}), 6773 data = createMap(), 6774 capacity = (options && options.capacity) || Number.MAX_VALUE, 6775 lruHash = createMap(), 6776 freshEnd = null, 6777 staleEnd = null; 6778 6779 /** 6780 * @ngdoc type 6781 * @name $cacheFactory.Cache 6782 * 6783 * @description 6784 * A cache object used to store and retrieve data, primarily used by 6785 * {@link $http $http} and the {@link ng.directive:script script} directive to cache 6786 * templates and other data. 6787 * 6788 * ```js 6789 * angular.module('superCache') 6790 * .factory('superCache', ['$cacheFactory', function($cacheFactory) { 6791 * return $cacheFactory('super-cache'); 6792 * }]); 6793 * ``` 6794 * 6795 * Example test: 6796 * 6797 * ```js 6798 * it('should behave like a cache', inject(function(superCache) { 6799 * superCache.put('key', 'value'); 6800 * superCache.put('another key', 'another value'); 6801 * 6802 * expect(superCache.info()).toEqual({ 6803 * id: 'super-cache', 6804 * size: 2 6805 * }); 6806 * 6807 * superCache.remove('another key'); 6808 * expect(superCache.get('another key')).toBeUndefined(); 6809 * 6810 * superCache.removeAll(); 6811 * expect(superCache.info()).toEqual({ 6812 * id: 'super-cache', 6813 * size: 0 6814 * }); 6815 * })); 6816 * ``` 6817 */ 6818 return (caches[cacheId] = { 6819 6820 /** 6821 * @ngdoc method 6822 * @name $cacheFactory.Cache#put 6823 * @kind function 6824 * 6825 * @description 6826 * Inserts a named entry into the {@link $cacheFactory.Cache Cache} object to be 6827 * retrieved later, and incrementing the size of the cache if the key was not already 6828 * present in the cache. If behaving like an LRU cache, it will also remove stale 6829 * entries from the set. 6830 * 6831 * It will not insert undefined values into the cache. 6832 * 6833 * @param {string} key the key under which the cached data is stored. 6834 * @param {*} value the value to store alongside the key. If it is undefined, the key 6835 * will not be stored. 6836 * @returns {*} the value stored. 6837 */ 6838 put: function(key, value) { 6839 if (isUndefined(value)) return; 6840 if (capacity < Number.MAX_VALUE) { 6841 var lruEntry = lruHash[key] || (lruHash[key] = {key: key}); 6842 6843 refresh(lruEntry); 6844 } 6845 6846 if (!(key in data)) size++; 6847 data[key] = value; 6848 6849 if (size > capacity) { 6850 this.remove(staleEnd.key); 6851 } 6852 6853 return value; 6854 }, 6855 6856 /** 6857 * @ngdoc method 6858 * @name $cacheFactory.Cache#get 6859 * @kind function 6860 * 6861 * @description 6862 * Retrieves named data stored in the {@link $cacheFactory.Cache Cache} object. 6863 * 6864 * @param {string} key the key of the data to be retrieved 6865 * @returns {*} the value stored. 6866 */ 6867 get: function(key) { 6868 if (capacity < Number.MAX_VALUE) { 6869 var lruEntry = lruHash[key]; 6870 6871 if (!lruEntry) return; 6872 6873 refresh(lruEntry); 6874 } 6875 6876 return data[key]; 6877 }, 6878 6879 6880 /** 6881 * @ngdoc method 6882 * @name $cacheFactory.Cache#remove 6883 * @kind function 6884 * 6885 * @description 6886 * Removes an entry from the {@link $cacheFactory.Cache Cache} object. 6887 * 6888 * @param {string} key the key of the entry to be removed 6889 */ 6890 remove: function(key) { 6891 if (capacity < Number.MAX_VALUE) { 6892 var lruEntry = lruHash[key]; 6893 6894 if (!lruEntry) return; 6895 6896 if (lruEntry === freshEnd) freshEnd = lruEntry.p; 6897 if (lruEntry === staleEnd) staleEnd = lruEntry.n; 6898 link(lruEntry.n,lruEntry.p); 6899 6900 delete lruHash[key]; 6901 } 6902 6903 if (!(key in data)) return; 6904 6905 delete data[key]; 6906 size--; 6907 }, 6908 6909 6910 /** 6911 * @ngdoc method 6912 * @name $cacheFactory.Cache#removeAll 6913 * @kind function 6914 * 6915 * @description 6916 * Clears the cache object of any entries. 6917 */ 6918 removeAll: function() { 6919 data = createMap(); 6920 size = 0; 6921 lruHash = createMap(); 6922 freshEnd = staleEnd = null; 6923 }, 6924 6925 6926 /** 6927 * @ngdoc method 6928 * @name $cacheFactory.Cache#destroy 6929 * @kind function 6930 * 6931 * @description 6932 * Destroys the {@link $cacheFactory.Cache Cache} object entirely, 6933 * removing it from the {@link $cacheFactory $cacheFactory} set. 6934 */ 6935 destroy: function() { 6936 data = null; 6937 stats = null; 6938 lruHash = null; 6939 delete caches[cacheId]; 6940 }, 6941 6942 6943 /** 6944 * @ngdoc method 6945 * @name $cacheFactory.Cache#info 6946 * @kind function 6947 * 6948 * @description 6949 * Retrieve information regarding a particular {@link $cacheFactory.Cache Cache}. 6950 * 6951 * @returns {object} an object with the following properties: 6952 * <ul> 6953 * <li>**id**: the id of the cache instance</li> 6954 * <li>**size**: the number of entries kept in the cache instance</li> 6955 * <li>**...**: any additional properties from the options object when creating the 6956 * cache.</li> 6957 * </ul> 6958 */ 6959 info: function() { 6960 return extend({}, stats, {size: size}); 6961 } 6962 }); 6963 6964 6965 /** 6966 * makes the `entry` the freshEnd of the LRU linked list 6967 */ 6968 function refresh(entry) { 6969 if (entry !== freshEnd) { 6970 if (!staleEnd) { 6971 staleEnd = entry; 6972 } else if (staleEnd === entry) { 6973 staleEnd = entry.n; 6974 } 6975 6976 link(entry.n, entry.p); 6977 link(entry, freshEnd); 6978 freshEnd = entry; 6979 freshEnd.n = null; 6980 } 6981 } 6982 6983 6984 /** 6985 * bidirectionally links two entries of the LRU linked list 6986 */ 6987 function link(nextEntry, prevEntry) { 6988 if (nextEntry !== prevEntry) { 6989 if (nextEntry) nextEntry.p = prevEntry; //p stands for previous, 'prev' didn't minify 6990 if (prevEntry) prevEntry.n = nextEntry; //n stands for next, 'next' didn't minify 6991 } 6992 } 6993 } 6994 6995 6996 /** 6997 * @ngdoc method 6998 * @name $cacheFactory#info 6999 * 7000 * @description 7001 * Get information about all the caches that have been created 7002 * 7003 * @returns {Object} - key-value map of `cacheId` to the result of calling `cache#info` 7004 */ 7005 cacheFactory.info = function() { 7006 var info = {}; 7007 forEach(caches, function(cache, cacheId) { 7008 info[cacheId] = cache.info(); 7009 }); 7010 return info; 7011 }; 7012 7013 7014 /** 7015 * @ngdoc method 7016 * @name $cacheFactory#get 7017 * 7018 * @description 7019 * Get access to a cache object by the `cacheId` used when it was created. 7020 * 7021 * @param {string} cacheId Name or id of a cache to access. 7022 * @returns {object} Cache object identified by the cacheId or undefined if no such cache. 7023 */ 7024 cacheFactory.get = function(cacheId) { 7025 return caches[cacheId]; 7026 }; 7027 7028 7029 return cacheFactory; 7030 }; 7031} 7032 7033/** 7034 * @ngdoc service 7035 * @name $templateCache 7036 * @this 7037 * 7038 * @description 7039 * The first time a template is used, it is loaded in the template cache for quick retrieval. You 7040 * can load templates directly into the cache in a `script` tag, or by consuming the 7041 * `$templateCache` service directly. 7042 * 7043 * Adding via the `script` tag: 7044 * 7045 * ```html 7046 * <script type="text/ng-template" id="templateId.html"> 7047 * <p>This is the content of the template</p> 7048 * </script> 7049 * ``` 7050 * 7051 * **Note:** the `script` tag containing the template does not need to be included in the `head` of 7052 * the document, but it must be a descendent of the {@link ng.$rootElement $rootElement} (IE, 7053 * element with ng-app attribute), otherwise the template will be ignored. 7054 * 7055 * Adding via the `$templateCache` service: 7056 * 7057 * ```js 7058 * var myApp = angular.module('myApp', []); 7059 * myApp.run(function($templateCache) { 7060 * $templateCache.put('templateId.html', 'This is the content of the template'); 7061 * }); 7062 * ``` 7063 * 7064 * To retrieve the template later, simply use it in your component: 7065 * ```js 7066 * myApp.component('myComponent', { 7067 * templateUrl: 'templateId.html' 7068 * }); 7069 * ``` 7070 * 7071 * or get it via the `$templateCache` service: 7072 * ```js 7073 * $templateCache.get('templateId.html') 7074 * ``` 7075 * 7076 * See {@link ng.$cacheFactory $cacheFactory}.
vendor: 5,589 bytes, lines 7076-7205
7076 7077 * 7078 */ 7079function $TemplateCacheProvider() { 7080 this.$get = ['$cacheFactory', function($cacheFactory) { 7081 return $cacheFactory('templates'); 7082 }]; 7083} 7084 7085/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * 7086 * Any commits to this file should be reviewed with security in mind. * 7087 * Changes to this file can potentially create security vulnerabilities. * 7088 * An approval from 2 Core members with history of modifying * 7089 * this file is required. * 7090 * * 7091 * Does the change somehow allow for arbitrary javascript to be executed? * 7092 * Or allows for someone to change the prototype of built-in objects? * 7093 * Or gives undesired access to variables like document or window? * 7094 * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ 7095 7096/* ! VARIABLE/FUNCTION NAMING CONVENTIONS THAT APPLY TO THIS FILE! 7097 * 7098 * DOM-related variables: 7099 * 7100 * - "node" - DOM Node 7101 * - "element" - DOM Element or Node 7102 * - "$node" or "$element" - jqLite-wrapped node or element 7103 * 7104 * 7105 * Compiler related stuff: 7106 * 7107 * - "linkFn" - linking fn of a single directive 7108 * - "nodeLinkFn" - function that aggregates all linking fns for a particular node 7109 * - "childLinkFn" - function that aggregates all linking fns for child nodes of a particular node 7110 * - "compositeLinkFn" - function that aggregates all linking fns for a compilation root (nodeList) 7111 */ 7112 7113 7114/** 7115 * @ngdoc service 7116 * @name $compile 7117 * @kind function 7118 * 7119 * @description 7120 * Compiles an HTML string or DOM into a template and produces a template function, which 7121 * can then be used to link {@link ng.$rootScope.Scope `scope`} and the template together. 7122 * 7123 * The compilation is a process of walking the DOM tree and matching DOM elements to 7124 * {@link ng.$compileProvider#directive directives}. 7125 * 7126 * <div class="alert alert-warning"> 7127 * **Note:** This document is an in-depth reference of all directive options. 7128 * For a gentle introduction to directives with examples of common use cases, 7129 * see the {@link guide/directive directive guide}. 7130 * </div> 7131 * 7132 * ## Comprehensive Directive API 7133 * 7134 * There are many different options for a directive. 7135 * 7136 * The difference resides in the return value of the factory function. 7137 * You can either return a {@link $compile#directive-definition-object Directive Definition Object (see below)} 7138 * that defines the directive properties, or just the `postLink` function (all other properties will have 7139 * the default values). 7140 * 7141 * <div class="alert alert-success"> 7142 * **Best Practice:** It's recommended to use the "directive definition object" form. 7143 * </div> 7144 * 7145 * Here's an example directive declared with a Directive Definition Object: 7146 * 7147 * ```js 7148 * var myModule = angular.module(...); 7149 * 7150 * myModule.directive('directiveName', function factory(injectables) { 7151 * var directiveDefinitionObject = { 7152 * {@link $compile#-priority- priority}: 0, 7153 * {@link $compile#-template- template}: '<div></div>', // or // function(tElement, tAttrs) { ... }, 7154 * // or 7155 * // {@link $compile#-templateurl- templateUrl}: 'directive.html', // or // function(tElement, tAttrs) { ... }, 7156 * {@link $compile#-transclude- transclude}: false, 7157 * {@link $compile#-restrict- restrict}: 'A', 7158 * {@link $compile#-templatenamespace- templateNamespace}: 'html', 7159 * {@link $compile#-scope- scope}: false, 7160 * {@link $compile#-controller- controller}: function($scope, $element, $attrs, $transclude, otherInjectables) { ... }, 7161 * {@link $compile#-controlleras- controllerAs}: 'stringIdentifier', 7162 * {@link $compile#-bindtocontroller- bindToController}: false, 7163 * {@link $compile#-require- require}: 'siblingDirectiveName', // or // ['^parentDirectiveName', '?optionalDirectiveName', '?^optionalParent'], 7164 * {@link $compile#-multielement- multiElement}: false, 7165 * {@link $compile#-compile- compile}: function compile(tElement, tAttrs, transclude) { 7166 * return { 7167 * {@link $compile#pre-linking-function pre}: function preLink(scope, iElement, iAttrs, controller) { ... }, 7168 * {@link $compile#post-linking-function post}: function postLink(scope, iElement, iAttrs, controller) { ... } 7169 * } 7170 * // or 7171 * // return function postLink( ... ) { ... } 7172 * }, 7173 * // or 7174 * // {@link $compile#-link- link}: { 7175 * // {@link $compile#pre-linking-function pre}: function preLink(scope, iElement, iAttrs, controller) { ... }, 7176 * // {@link $compile#post-linking-function post}: function postLink(scope, iElement, iAttrs, controller) { ... } 7177 * // } 7178 * // or 7179 * // {@link $compile#-link- link}: function postLink( ... ) { ... } 7180 * }; 7181 * return directiveDefinitionObject; 7182 * }); 7183 * ``` 7184 * 7185 * <div class="alert alert-warning"> 7186 * **Note:** Any unspecified options will use the default value. You can see the default values below. 7187 * </div> 7188 * 7189 * Therefore the above can be simplified as: 7190 * 7191 * ```js 7192 * var myModule = angular.module(...); 7193 * 7194 * myModule.directive('directiveName', function factory(injectables) { 7195 * var directiveDefinitionObject = { 7196 * link: function postLink(scope, iElement, iAttrs) { ... } 7197 * }; 7198 * return directiveDefinitionObject; 7199 * // or 7200 * // return function postLink(scope, iElement, iAttrs) { ... } 7201 * }); 7202 * ``` 7203 * 7204 * ### Life-cycle hooks 7205 * Directive controllers can provide the following methods that are called by Angular
7205 at points in the life-cycle of the 7206 * directive: 7207 * * `$onInit()` - Called on each controller after all the controllers on an element have been constructed and 7208 * had their bindings initialized (and before the pre & post linking functions for the directives on 7209 * this element). This is a good place to put initialization code for your controller. 7210 * * `$onChanges(changesObj)` - Called whenever one-way (`<`) or interpolation (`@`) bindings are updated. The 7211 * `changesObj` is a hash whose keys are the names of the bound properties that have changed, and the values are an 7212 * object of the form `{ currentValue, previousValue, isFirstChange() }`. Use this hook to trigger updates within a 7213 * component such as cloning the bound value to prevent accidental mutation of the outer value. Note that this will 7214 * also be called when your bindings are initialized. 7215 * * `$doCheck()` - Called on each turn of the digest cycle. Provides an opportunity to detect and act on 7216 * changes. Any actions that you wish to take in response to the changes that you detect must be 7217 * invoked from this hook; implementing this has no effect on when `$onChanges` is called. For example, this hook 7218 * could be useful if you wish to perform a deep equality check, or to check a Date object, changes to which w
7218ould not 7219 * be detected by Angular's change detector and thus not trigger `$onChanges`. This hook is invoked with no arguments; 7220 * if detecting changes, you must store the previous value(s) for comparison to the current values. 7221 * * `$onDestroy()` - Called on a controller when its containing scope is destroyed. Use this hook for releasing 7222 * external resources, watches and event handlers. Note that components have their `$onDestroy()` hooks called in 7223 * the same order as the `$scope.$broadcast` events are triggered, which is top down. This means that parent 7224 * components will have their `$onDestroy()` hook called before child components. 7225 * * `$postLink()` - Called after this controller's element and its children have been linked. Similar to the post-link 7226 * function this hook can be used to set up DOM event handlers and do direct DOM manipulation. 7227 * Note that child elements that contain `templateUrl` directives will not have been compiled and linked since 7228 * they are waiting for their template to load asynchronously and their own compilation and linking has been 7229 * suspended until that occurs. 7230 * 7231 * #### Comparison with Angular 2 life-cycle hooks 7232 * Angular 2 also uses life-cycle hooks for its components. While the Angular 1 life-cycle hooks are similar there are 7233 * some differences that you should be aware of, especially when it comes to moving your co
7233de from Angular 1 to Angular 2: 7234 * 7235 * * Angular 1 hooks are prefixed with `$`, such as `$onInit`. Angular 2 hooks are prefixed with `ng`, such as `ngOnInit`. 7236 * * Angular 1 hooks can be defined on the controller prototype or added to the controller inside its constructor. 7237 * In Angular 2 you can only define hooks on the prototype of the Component class. 7238 * * Due to the differences in change-detection, you may get many more calls to `$doCheck` in Angular 1 than you would to 7239 * `ngDoCheck` in Angular 2 7240 * * Changes to the model inside `$doCheck` will trigger new turns of the digest loop, which will cause the changes to be 7241 * propagated throughout the application. 7242 * Angular 2 does not allow the `ngDoCheck` hook to trigger a change outside of the component. It will either throw an 7243 * error or do nothing depending upon the state of `enableProdMode()`. 7244 * 7245 * #### Life-cycle hook examples 7246 * 7247 * This example shows how you can check for mutations to a Date object even though the identity of the object 7248 * has not changed. 7249 * 7250 * <example name="doCheckDateExample" module="do-check-module"> 7251 * <file name="app.js"> 7252 * angular.module('do-check-module', []) 7253 * .component('app', { 7254 * template: 7255 * 'Month: <input ng-model="$ctrl.month" ng-change="$ctrl.updateDate()">' + 7256 * 'Date: {{ $ctrl.date }}' + 7257 * '<test date="$ctrl.date"></test>', 7258 * controller: function() { 7259 * this.date = new Date(); 7260 * this.month = this.date.getMonth(); 7261 * this.updateDate = function() { 7262 * this.date.setMonth(this.month); 7263 * }; 7264 * } 7265 * }) 7266 * .component('test', { 7267 * bindings: { date: '<' }, 7268 * template: 7269 * '<pre>{{ $ctrl.log | json }}</pre>', 7270 * controller: function() { 7271 * var previousValue; 7272 * this.log = []; 7273 * this.$doCheck = function() { 7274 * var currentValue = this.date && this.date.valueOf(); 7275 * if (previousValue !== currentValue) { 7276 * this.log.push('doCheck: date mutated: ' + this.date); 7277 * previousValue = currentValue; 7278 * } 7279 * }; 7280 * } 7281 * }); 7282 * </file> 7283 * <file name="index.html"> 7284 * <app></app> 7285 * </file> 7286 * </example> 7287 * 7288 * This example show how you might use `$doCheck` to trigger changes in your component's input
7288s even if the 7289 * actual identity of the component doesn't change. (Be aware that cloning and deep equality checks on large 7290 * arrays or objects can have a negative impact on your application performance) 7291 * 7292 * <example name="doCheckArrayExample" module="do-check-module"> 7293 * <file name="index.html"> 7294 * <div ng-init="items = []"> 7295 * <button ng-click="items.push(items.length)">Add Item</button> 7296 * <button ng-click="items = []">Reset Items</button> 7297 * <pre>{{ items }}</pre> 7298 * <test items="items"></test> 7299 * </div> 7300 * </file> 7301 * <file name="app.js"> 7302 * angular.module('do-check-module', []) 7303 * .component('test', { 7304 * bindings: { items: '<' }, 7305 * template: 7306 * '<pre>{{ $ctrl.log | json }}</pre>', 7307 * controller: function() { 7308 * this.log = []; 7309 * 7310 * this.$doCheck = function() { 7311 * if (this.items_ref !== this.items) { 7312 * this.log.push('doCheck: items changed'); 7313 * this.items_ref = this.items; 7314 * } 7315 * if (!angular.equals(this.items_clone, this.items)) { 7316 * this.log.push('doCheck: items mutated'); 7317 * this.items_clone = angular.copy(this.items); 7318 * } 7319 * }; 7320 * } 7321 * }); 7322 * </file> 7323 * </example> 7324 * 7325 * 7326 * ### Directive Definition Object 7327 * 7328 * The directive definition object provides instructions to the {@link ng.$compile 7329 * compiler}. The attributes are: 7330 * 7331 * #### `multiElement` 7332 * When this property is set to true (default is `false`), the HTML compiler will collect DOM nodes between 7333 * nodes with the attributes `directive-name-start` and `directive-name-end`, and group them 7334 * together as the directive elements. It is recommended that this feature be used on directives 7335 * which are not strictly behavioral (such as {@link ngClick}), and which 7336 * do not manipulate or replace child nodes (such as {@link ngInclude}). 7337 * 7338 * #### `priority` 7339 * When there are multiple directives defined on a single DOM element, sometimes it 7340 * is necessary to specify the order in which the directives are applied. The `priority` is used 7341 * to sort the directives before their `compile` functions get called. Priority is defined as a 7342 * number. Directives with greater numerical `priority` are compiled first. Pre-link functions 7343 * are also run in priority order, but post-link functions are run in reverse order. The order 7344 * of directives with the same priority is undefined. The default priority is `0`. 7345 * 7346 * #### `terminal` 7347 * If set to true then the current `priority` will be the last set of directives 7348 * which will execute (any directives at the current priority will still execute 7349 * as the order of execution on same `priority` is undefined). Note that expressions 7350 * and other directives used in the directive's template will also be excluded from execution. 7351 * 7352 * #### `scope` 7353 * The scope property can be `false`, `true`, or an object: 7354 * 7355 * * **`false` (default):** No scope will be created for the directive. The directive will use its 7356 * parent's scope. 7357 * 7358 * * **`true`:** A new child scope that prototypically inherits from its parent will be created for 7359 * the directive's element. If multiple directives on the same element request a new scope, 7360 * only one new scope is created. 7361 * 7362 * * **`{...}` (an object hash):** A new "isolate" scope is created for the directive's template. 7363 * The 'isolate' scope differs from normal scope in that it does not prototypically 7364 * inherit from its parent scope. This is useful when creating reusable components, which should not 7365 * accidentally read or modify data in the parent scope. Note that an isolate scope 7366 * directive without a `template` or `templateUrl` will not apply the isolate scope 7367 * to its children elements. 7368 * 7369 * The 'isolate' scope object hash defines a set of local scope properties derived from attributes on the 7370 * directive's element. These local properties are useful for aliasing values for templates. The keys in 7371 * the object hash map to the name of the property on the isolate scope; the values define how the property 7372 * is bound to the parent scope, via matching attributes on the directive's element: 7373 * 7374 * * `@` or `@attr` - bind a local scope property to the value of DOM attribute. The result is
7375 * always a string since DOM attributes are strings. If no `attr` name is specified then the 7376 * attribute name is assumed to be the same as the local name. Given `<my-component 7377 * my-attr="hello {{name}}">` and the isolate scope definition `scope: { localName:'@myAttr' }`, 7378 * the directive's scope property `localName` will reflect the interpolated value of `hello 7379 * {{name}}`. As the `name` attribute changes so will the `localName` property on the directive's 7380 * scope. The `name` is read from the parent scope (not the directive's scope). 7381 * 7382 * * `=` or `=attr` - set up a bidirectional binding between a local scope property and an expression 7383 * passed via the attribute `attr`. The expression is evaluated in the context of the parent scope. 7384 * If no `attr` name is specified then the attribute name is assumed to be the same as the local 7385 * name. Given `<my-component my-attr="parentModel">` and the isolate scope definition `scope: { 7386 * localModel: '=myAttr' }`, the property `localModel` on the directive's scope will reflect the 7387 * value of `parentModel` on the parent scope. Changes to `parentModel` will be reflected in 7388 * `localModel` and vice versa. Optional attributes should be marked as such with a question mark: 7389 * `=?` or `=?attr`. If the binding expression is non-assignable, or if the attribute isn't 7390 * optional and doesn't exist, an exception ({@link error/$compile/nonassign `$compile:nonassign`}) 7391 * will be thrown upon discovering changes to the local value, since it will be impossible to sync 7392 * them back to the parent scope. By default, the {@link ng.$rootScope.Scope#$watch `$watch`} 7393 * method is used for tracking changes, and the equality check is based on object identity. 7394 * However, if an object literal or an array literal is passed as the binding expression, the 7395 * equality check is done by value (using the {@link angular.equals} function). It's also possible 7396 * to watch the evaluated value shallowly with {@link ng.$rootScope.Scope#$watchCollection 7397 * `$watchCollection`}: use `=*` or `=*attr` (`=*?` or `=*?attr` if the attribute is optional). 7398 * 7399 * * `<` or `<attr` - set up a one-way (one-directional) binding between a local scope property and an 7400 * expression passed via the attribute `attr`. The expression is evaluated in the context of the 7401 * parent scope. If no `attr` name is specified then the attribute name is assumed to be the same as the 7402 * local name. You can also make the binding optional by adding `?`: `<?` or `<?attr`. 7403 * 7404 * For example, given `<my-component my-attr="parentModel">` and directive definition of 7405 * `scope: { localModel:'<myAttr' }`, then the isolated scope property `localModel` will reflect the 7406 * value of `parentModel` on the parent scope. Any changes to `parentModel` will be reflected 7407 * in `localModel`, but changes in `localModel` will not reflect in `parentModel`. There are however 7408 * two caveats: 7409 * 1. one-way binding does not copy the value from the parent to the isolate scope, it simply 7410 * sets the same value. That means if your bound value is an object, changes to its properties 7411 * in the isolated scope will be reflected in the parent scope (because both reference the same object). 7412 * 2. one-way binding watches changes to the **identity** of the parent value. That means the 7413 * {@link ng.$rootScope.Scope#$watch `$watch`} on the parent value only fires if the reference 7414 * to the value has changed. In most cases, this should not be of concern, but can be important 7415 * to know if you one-way bind to an object, and then replace that object in the isolated scope. 7416 * If you now change a property of the object in your parent scope, the change will not be 7417 * propagated to the isolated scope, because the identity of the object on the parent scope 7418 * has not changed. Instead you must assign a new object. 7419 * 7420 * One-way binding is useful if you do not plan to propagate changes to your isolated scope bindings 7421 * back to the parent. However, it does not make this completely impossible. 7422 * 7423 * * `&` or `&attr` - provides a way to execute an expression in the context of the parent scope. If 7424 * no `attr` name is specified then the attribute name is assumed to be the same as the local name. 7425 * Given `<my-component my-attr="count = count + value">` and the isolate scope definition `scope: { 7426 * localFn:'&myAttr' }`, the isolate scope property `localFn` will point to a function wrapper for 7427 * the `count = count + value` expression. Often it's desirable to pass data from the isolated scope 7428 * via an expression to the parent scope. This can be done by passing a map of local variable names 7429 * and values into the expression wrapper fn. For example, if the expression is `increment(amount)` 7430 * then we can specify the amount value by calling the `localFn` as `localFn({amount: 22})`. 7431 * 7432 * In general it's possible to apply more than one directive to one element, but there might be limitations 7433 * depending on the type of scope required by the directives. The following points will help explain these limitations. 7434 * For simplicity only two directives are taken into account, but it is also applicable for several directives: 7435 * 7436 * * **no scope** + **no scope** => Two directives which don't require their own scope will use their parent's scope 7437 * * **child scope** + **no scope** => Both directives will share one single child scope 7438 * * **child scope** + **child scope** => Both directives will share one single child scope 7439 * * **isolated scope** + **no scope** => The isolated directive will use it's own created isolated scope. The other directive will use 7440 * its parent's scope 7441 * * **isolated scope** + **child scope** => **Won't work!** Only one scope can be related to one element. Therefore these directives cannot 7442 * be applied to the same element. 7443 * * **isolated scope** + **isolated scope** => **Won't work!** Only one scope can be related to one element. Therefore these directives 7444 * cannot be applied to the same element. 7445 * 7446 * 7447 * #### `bindToController` 7448 * This property is used to bind scope properties directly to the controller. It can be either 7449 * `true` or an object hash with the same format as the `scope` property. 7450 * 7451 * When an isolate scope is used for a directive (see above), `bindToController: true` will 7452 * allow a component to have its properties bound to the controller, rather than to scope. 7453 * 7454 * After the controller is instantiated, the initial values of the isolate scope bindings will be bound to the controller 7455 * properties. You can access these bindings once they have been initialized by providing a controller method called 7456 * `$onInit`, which is called after all the controllers on an element have been constructed and had their bindings 7457 * initialized. 7458 * 7459 * <div class="alert alert-warning"> 7460 * **Deprecation warning:** if `$compileProcvider.preAssignBindingsEnabled(true)` was called, bindings for non-ES6 class 7461 * controllers are bound to `this` before the controller constructor is called but this use is now deprecated. Please 7462 * place initialization code that relies upon bindings inside a `$onInit` method on the controller, instead. 7463 * </div> 7464 * 7465 * It is also possible to set `bindToController` to an object hash with the same format as the `scope` property. 7466 * This will set up the scope bindings to the controller directly. Note that `scope` can still be used 7467 * to define which kind of scope is created. By default, no scope is created. Use `scope: {}` to create an isolate 7468 * scope (useful for component directives). 7469 * 7470 * If both `bindToController` and `scope` are defined and have object hashes, `bindToController` overrides `scope`. 7471 * 7472 * 7473 * #### `controller` 7474 * Controller constructor function. The controller is instantiated before the 7475 * pre-linking phase and can be accessed by other directives (see 7476 * `require` attribute). This allows the directives to communicate with each other and augment 7477 * each other's behavior. The controller is injectable (and supports bracket notation) with the following locals: 7478 * 7479 * * `$scope` - Current scope associated with the element 7480 * * `$element` - Current element 7481 * * `$attrs` - Current attributes object for the element 7482 * * `$transclude` - A transclude linking function pre-bound to the correct transclusion scope: 7483 * `function([scope], cloneLinkingFn, futureParentElement, slotName)`: 7484 * * `scope`: (optional) override the scope. 7485 * * `cloneLinkingFn`: (optional) argument to create clones of the original transcluded content. 7486 * * `futureParentElement` (optional): 7487 * * defines the parent to which the `cloneLinkingFn` will add the cloned elements. 7488 * * default: `$element.parent()` resp. `$element` for `transclude:'element'` resp. `transclude:true`. 7489 * * only needed for transcludes that are allowed to contain non html elements (e.g. SVG elements) 7490 * and when the `cloneLinkingFn` is passed, 7491 * as those elements need to created and cloned in a special way when they are defined outside their 7492 * usual containers (e.g. like `<svg>`). 7493 * * See also the `directive.templateNamespace` property. 7494 * * `slotName`: (optional) the name of the slot to transclude. If falsy (e.g. `null`, `undefined` or `''`) 7495 * then the default transclusion is provided. 7496 * The `$transclude` function also has a method on it, `$transclude.isSlotFilled(slotName)`, which returns 7497 * `true` if the specified slot contains content (i.e. one or more DOM nodes). 7498 * 7499 * #### `require` 7500 * Require another directive and inject its controller as the fourth argument to the linking function. The 7501 * `require` property can be a string, an array or an object: 7502 * * a **string** containing the name of the directive to pass to the linking function 7503 * * an **array** containing the names of directives to pass to the linking function. The argument passed to the 7504 * linking function will be an array of controllers in the same order as the names in the `require` property 7505 * * an **object** whose property values are the names of the directives to pass to the linking function. The argument 7506 * passed to the linking function will also be an object with matching keys, whose values will hold the corresponding 7507 * controllers. 7508 * 7509 * If the `require` property is an object and `bindToController` is truthy, then the required controllers are 7510 * bound to the controller using the keys of the `require` property. This binding occurs after all the controllers 7511 * have been constructed but before `$onInit` is called. 7512 * If the name of the required controller is the same as the local name (the key), the name can be 7513 * omitted. For example, `{parentDir: '^^'}` is equivalent to `{parentDir: '^^parentDir'}`. 7514 * See the {@link $compileProvider#component} helper for an example of how this can be used. 7515 * If no such required directive(s) can be found, or if the directive does not have a controller, then an error is 7516 * raised (unless no link function is specified and the required controllers are not being bound to the directive 7517 * controller, in which case error checking is skipped). The name can be prefixed with: 7518 * 7519 * * (no prefix) - Locate the required controller on the current element. Throw an error if not found. 7520 * * `?` - Attempt to locate the required controller or pass `null` to the `link` fn if not found. 7521 * * `^` - Locate the required controller by searching the element and its parents. Throw an error if not found. 7522 * * `^^` - Locate the required controller by searching the element's parents. Throw an error if not found. 7523 * * `?^` - Attempt to locate the required controller by searching the element and its parents or pass 7524 * `null` to the `link` fn if not found. 7525 * * `?^^` - Attempt to locate the required controller by searching the element's parents, or pass 7526 * `null` to the `link` fn if not found. 7527 * 7528 * 7529 * #### `controllerAs` 7530 * Identifier name for a reference to the controller in the directive's scope. 7531 * This allows the controller to be referenced from the directive template. This is especially 7532 * useful when a directive is used as component, i.e. with an `isolate` scope. It's also possible 7533 * to use it in a directive without an `isolate` / `new` scope, but you need to be aware that the 7534 * `controllerAs` reference might overwrite a property that already exists on the parent scope. 7535 * 7536 * 7537 * #### `restrict` 7538 * String of subset of `EACM` which restricts the directive to a specific directive 7539 * declaration style. If omitted, the defaults (elements and attributes) are used. 7540 * 7541 * * `E` - Element name (default): `<my-directive></my-directive>` 7542 * * `A` - Attribute (default): `<div my-directive="exp"></div>` 7543 * * `C` - Class: `<div class="my-directive: exp;"></div>` 7544 * * `M` - Comment: `<!-- directive: my-directive exp -->` 7545 * 7546 * 7547 * #### `templateNamespace` 7548 * String representing the document type used by the markup in the template. 7549 * AngularJS needs this information as those elements need to be created and cloned 7550 * in a special way when they are defined outside their usual containers like `<svg>` and `<math>`. 7551 * 7552 * * `html` - All root nodes in the template are HTML. Root nodes may also be 7553 * top-level elements such as `<svg>` or `<math>`. 7554 * * `svg` - The root nodes in the template are SVG elements (excluding `<math>`). 7555 * * `math` - The root nodes in the template are MathML elements (excluding `<svg>`). 7556 * 7557 * If no `templateNamespace` is specified, then the namespace is considered to be `html`. 7558 * 7559 * #### `template` 7560 * HTML markup that may: 7561 * * Replace the contents of the directive's element (default). 7562 * * Replace the directive's element itself (if `replace` is true - DEPRECATED). 7563 * * Wrap the contents of the directive's element (if `transclude` is true). 7564 * 7565 * Value may be: 7566 * 7567 * * A string. For example `<div red-on-hover>{{delete_str}}</div>`. 7568 * * A function which takes two arguments `tElement` and `tAttrs` (described
7568in the `compile` 7569 * function api below) and returns a string value. 7570 * 7571 * 7572 * #### `templateUrl` 7573 * This is similar to `template` but the template is loaded from the specified URL, asynchronously. 7574 * 7575 * Because template loading is asynchronous the compiler will suspend compilation of directives on that element 7576 * for later when the template has been resolved. In the meantime it will continue to compile and link 7577 * sibling and parent elements as though this element had not contained any directives. 7578 * 7579 * The compiler does not suspend the entire compilation to wait for templates to be loaded because this 7580 * would result in the whole app "stalling" until all templates are loaded asynchronously - even in the 7581 * case when only one deeply nested directive has `templateUrl`. 7582 * 7583 * Template loading is asynchronous even if the template has been preloaded into the {@link $templateCache} 7584 * 7585 * You can specify `templateUrl` as a string representing the URL or as a function which takes two 7586 * arguments `tElement` and `tAttrs` (described in the `compile` function api below) and returns 7587 * a string value representing the url. In either case, the template URL is passed through {@link 7588 * $sce#getTrustedResourceUrl $sce.getTrustedResourceUrl}. 7589 * 7590 * 7591 * #### `replace` ([*DEPRECATED*!], will be removed in next major release - i.e. v2.0) 7592 * specify what the template should replace. Defaults to `false`. 7593 * 7594 * * `true` - the template will replace the directive's element. 7595 * * `false` - the template will replace the contents of the directive's element. 7596 * 7597 * The replacement process migrates all of the attributes / classes from the old element to the new 7598 * one. See the {@link guide/directive#template-expanding-directive 7599 * Directives Guide} for an example. 7600 * 7601 * There are very few scenarios where element replacement is required for the application function, 7602 * the main one being reusable custom components that are used within SVG contexts 7603 * (because SVG doesn't work with custom elements in the DOM tree). 7604 * 7605 * #### `transclude` 7606 * Extract the contents of the element where the directive appears and make it available to the directive. 7607 * The contents are compiled and provided to the directive as a **transclusion function**. See the 7608 * {@link $compile#transclusion Transclusion} section below. 7609 * 7610 * 7611 * #### `compile` 7612 * 7613 * ```js 7614 * function compile(tElement, tAttrs, transclude) { ... } 7615 * ``` 7616 * 7617 * The compile function deals with transforming the template DOM. Since most directives do not do 7618 * template transformation, it is not used often. The compile function takes the following arguments: 7619 * 7620 * * `tElement` - template element - The element where the directive has been declared. It is 7621 * safe to do template transformation on the element and child elements only. 7622 * 7623 * * `tAttrs` - template attributes - Normalized list of attributes declared on this element shared 7624 * between all directive compile functions. 7625 * 7626 * * `transclude` - [*DEPRECATED*!] A transclude linking function: `function(scope, cloneLinkingFn)` 7627 * 7628 * <div class="alert alert-warning"> 7629 * **Note:** The template instance and the link instance may be different objects if the template has 7630 * been cloned. For this reason it is **not** safe to do anything other than DOM transformations that 7631 * apply to all cloned DOM nodes within the compile function. Specifically, DOM listener registration 7632 * should be done in a linking function rather than in a compile function. 7633 * </div> 7634 7635 * <div class="alert alert-warning"> 7636 * **Note:** The compile function cannot handle directives that recursively use themselves in their 7637 * own templates or compile functions. Compiling these directives results in an infinite loop and 7638 * stack overflow errors. 7639 * 7640 * This can be avoided by manually using $compile
vendor: 5,458 bytes, lines 7640-7744
7640 in the postLink function to imperatively compile 7641 * a directive's template instead of relying on automatic template compilation via `template` or 7642 * `templateUrl` declaration or manual compilation inside the compile function. 7643 * </div> 7644 * 7645 * <div class="alert alert-danger"> 7646 * **Note:** The `transclude` function that is passed to the compile function is deprecated, as it 7647 * e.g. does not know about the right outer scope. Please use the transclude function that is passed 7648 * to the link function instead. 7649 * </div> 7650 7651 * A compile function can have a return value which can be either a function or an object. 7652 * 7653 * * returning a (post-link) function - is equivalent to registering the linking function via the 7654 * `link` property of the config object when the compile function is empty. 7655 * 7656 * * returning an object with function(s) registered via `pre` and `post` properties - allows you to 7657 * control when a linking function should be called during the linking phase. See info about 7658 * pre-linking and post-linking functions below. 7659 * 7660 * 7661 * #### `link` 7662 * This property is used only if the `compile` property is not defined. 7663 * 7664 * ```js 7665 * function link(scope, iElement, iAttrs, controller, transcludeFn) { ... } 7666 * ``` 7667 * 7668 * The link function is responsible for registering DOM listeners as well as updating the DOM. It is 7669 * executed after the template has been cloned. This is where most of the directive logic will be 7670 * put. 7671 * 7672 * * `scope` - {@link ng.$rootScope.Scope Scope} - The scope to be used by the 7673 * directive for registering {@link ng.$rootScope.Scope#$watch watches}. 7674 * 7675 * * `iElement` - instance element - The element where the directive is to be used. It is safe to 7676 * manipulate the children of the element only in `postLink` function since the children have 7677 * already been linked. 7678 * 7679 * * `iAttrs` - instance attributes - Normalized list of attributes declared on this element shared 7680 * between all directive linking functions. 7681 * 7682 * * `controller` - the directive's required controller instance(s) - Instances are shared 7683 * among all directives, which allows the directives to use the controllers as a communication 7684 * channel. The exact value depends on the directive's `require` property: 7685 * * no controller(s) required: the directive's own controller, or `undefined` if it doesn't have one 7686 * * `string`: the controller instance 7687 * * `array`: array of controller instances 7688 * 7689 * If a required controller cannot be found, and it is optional, the instance is `null`, 7690 * otherwise the {@link error:$compile:ctreq Missing Required Controller} error is thrown. 7691 * 7692 * Note that you can also require the directive's own controller - it will be made available like 7693 * any other controller. 7694 * 7695 * * `transcludeFn` - A transclude linking function pre-bound to the correct transclusion scope. 7696 * This is the same as the `$transclude` parameter of directive controllers, 7697 * see {@link ng.$compile#-controller- the controller section for details}. 7698 * `function([scope], cloneLinkingFn, futureParentElement)`. 7699 * 7700 * #### Pre-linking function 7701 * 7702 * Executed before the child elements are linked. Not safe to do DOM transformation since the 7703 * compiler linking function will fail to locate the correct elements for linking. 7704 * 7705 * #### Post-linking function 7706 * 7707 * Executed after the child elements are linked. 7708 * 7709 * Note that child elements that contain `templateUrl` directives will not have been compiled 7710 * and linked since they are waiting for their template to load asynchronously and their own 7711 * compilation and linking has been suspended until that occurs. 7712 * 7713 * It is safe to do DOM transformation in the post-linking function on elements that are not waiting 7714 * for their async templates to be resolved. 7715 * 7716 * 7717 * ### Transclusion 7718 * 7719 * Transclusion is the process of extracting a collection of DOM elements from one part of the DOM and 7720 * copying them to another part of the DOM, while maintaining their connection to the original AngularJS 7721 * scope from where they were taken. 7722 * 7723 * Transclusion is used (often with {@link ngTransclude}) to insert the 7724 * original contents of a directive's element into a specified place in the template of the directive. 7725 * The benefit of transclusion, over simply moving the DOM elements manually, is that the transcluded 7726 * content has access to the properties on the scope from which it was taken, even if the directive 7727 * has isolated scope. 7728 * See the {@link guide/directive#creating-a-directive-that-wraps-other-elements Directives Guide}. 7729 * 7730 * This makes it possible for the widget to have private state for its template, while the transcluded 7731 * content has access to its originating scope. 7732 * 7733 * <div class="alert alert-warning"> 7734 * **Note:** When testing an element transclude directive you must not place the directive at the root of the 7735 * DOM fragment that is being compiled. See {@link guide/unit-testing#testing-transclusion-directives 7736 * Testing Transclusion Directives}. 7737 * </div> 7738 * 7739 * There are three kinds of transclusion depending upon whether you want to transclude just the contents of the 7740 * directive's element, the entire element or multiple parts of the element contents: 7741 * 7742 * * `true` - transclude the content (i.e. the child nodes) of the directive's element. 7743 * * `'element'` - transclude the whole of the directive's element including any directives on this 7744 * element that
7744defined at a lower priority than this directive. When used, the `template` 7745 * property is ignored. 7746 * * **`{...}` (an object hash):** - map elements of the content onto transclusion "slots" in the template. 7747 * 7748 * **Mult-slot transclusion** is declared by providing an object for the `transclude` property. 7749 * 7750 * This object is a map where the keys are the name of the slot to fill and the value is an element selector 7751 * used to match the HTML to the slot. The element selector should be in normalized form (e.g. `myElement`) 7752 * and will match the standard element variants (e.g. `my-element`, `my:element`, `data-my-element`, etc). 7753 * 7754 * For further information check out the guide on {@link guide/directive#matching-directives Matching Directives} 7755 * 7756 * If the element selector is prefixed with a `?` then that slot is optional. 7757 * 7758 * For example, the transclude object `{ slotA: '?myCustomElement' }` maps `<my-custom-element>` elements to 7759 * the `slotA` slot, which can be accessed via the `$transclude` function or via the {@link ngTransclude} directive. 7760 * 7761 * Slots that are not marked as optional (`?`) will trigger a compile time error if there are no matching elements 7762 * in the transclude content. If you wish to know if an optional slot was filled with content, then you can call 7763 * `$transclude.isSlotFilled(slotName)` on the transclude function passed to the directive's link function and 7764 * injectable into the directive's controller. 7765 * 7766 * 7767 * #### Transclusion Functions 7768 * 7769 * When a directive requests transclusion, the compiler extracts its contents and provides a **transclusion 7770 * function** to the directive's `link` function and `controller`. This transclusion function is a special 7771 * **linking function** that will return the compiled contents linked to a new transclusion scope. 7772 * 7773 * <div class="alert alert-info"> 7774 * If you are just using {@link ngTransclude} then you don't need to worry about this function, since 7775 * ngTransclude will deal with it for us. 7776 * </div> 7777 * 7778 * If you want to manually control the insertion and removal of the transcluded content in your directive 7779 * then you must use this transclude function. When you call a transclude function it returns a a jqLite/JQuery 7780 * object that contains the compiled DOM, which is linked to the correct transclusion scope. 7781 * 7782 * When you call a transclusion function you can pass in a **clone attach function**. This function accepts 7783 * two parameters, `function(clone, scope) { ... }`, where the `clone` is a fresh compiled copy of your transcluded 7784 * content and the `scope` is the newly created transclusion scope, which the clone will be linked to. 7785 * 7786 * <div class="alert alert-info"> 7787 * **Best Practice**: Always provide a `cloneFn` (clone attach function) when you call a transclude function 7788 * since you then get a fresh clone of the original DOM and also have access to the new transclusion scope. 7789 * </div> 7790 * 7791 * It is normal practice to attach your transcluded content (`clone`) to the DOM inside your **clone 7792 * attach function**: 7793 * 7794 * ```js 7795 * var transcludedContent, transclusionScope; 7796 * 7797 * $transclude(function(clone, scope) { 7798 * element.append(clone); 7799 * transcludedContent = clone; 7800 * transclusionScope = scope; 7801 * }); 7802 * ``` 7803 * 7804 * Later, if you want to remove the transcluded content from your DOM then you should also destroy the 7805 * associated transclusion scope: 7806 * 7807 * ```js 7808 * transcludedContent.remove(); 7809 * transclusionScope.$destroy(); 7810 * ``` 7811 * 7812 * <div class="alert alert-info"> 7813 * **Best Practice**: if you intend to add and remove transcluded content manually in your directive 7814 * (by calling the transclude function to get the DOM and calling `element.remove()` to remove it), 7815 * then you are also responsible for calling `$destroy` on the transclusion scope. 7816 * </div> 7817 * 7818 * The built-in DOM manipulation directives, such as {@link ngIf}, {@link ngSwitch} and {@link ngRepeat} 7819 * automatically destroy their transcluded clones as necessary so you do not need to worry about this if 7820 * you are simply using {@link ngTransclude} to inject the transclusion into your directive. 7821 * 7822 * 7823 * #### Transclusion Scopes 7824 * 7825 * When you call a transclude function it returns a DOM fragment that is pre-bound to a **transclusion 7826 * scope**. This scope is special, in that it is a child of the directive's scope (and so gets destroyed 7827 * when the directive's scope gets destroyed) but it inherits the properties of the scope from which it 7828 * was taken. 7829 * 7830 * For example consider a directive that uses transclusion and isolated scope. The DOM hierarchy might look 7831 * like this: 7832 * 7833 * ```html 7834 * <div ng-app> 7835 * <div isolate> 7836 * <div transclusion>
7837 * </div> 7838 * </div> 7839 * </div> 7840 * ``` 7841 * 7842 * The `$parent` scope hierarchy will look like this: 7843 * 7844 ``` 7845 - $rootScope 7846 - isolate 7847 - transclusion 7848 ``` 7849 * 7850 * but the scopes will inherit prototypically from different scopes to their `$parent`. 7851 * 7852 ``` 7853 - $rootScope 7854 - transclusion 7855 - isolate 7856 ``` 7857 * 7858 * 7859 * ### Attributes 7860 * 7861 * The {@link ng.$compile.directive.Attributes Attributes} object - passed as a parameter in the 7862 * `link()` or `compile()` functions. It has a variety of uses. 7863 * 7864 * * *Accessing normalized attribute names:* Directives like 'ngBind' can be expressed in many ways: 7865 * 'ng:bind', `data-ng-bind`, or 'x-ng-bind'. The attributes object allows for normalized access 7866 * to the attributes. 7867 * 7868 * * *Directive inter-communication:* All directives share the same instance of the attributes 7869 * object which allows the directives to use the attributes object as inter directive 7870 * communication. 7871 * 7872 * * *Supports interpolation:* Interpolation attributes are assigned to the attribute object 7873 * allowing other directives to read the interpolated value. 7874 * 7875 * * *Observing interpolated attributes:* Use `$observe` to observe the value changes of attributes 7876 * that contain interpolation (e.g. `src="{{bar}}"`). Not only is this very efficient but it's also 7877 * the only way to easily get the actual value because during the linking phase the interpolation 7878 * hasn't been evaluated yet and so the value is at this time set to `undefined`. 7879 * 7880 * ```js 7881 * function linkingFn(scope, elm, attrs, ctrl) { 7882 * // get the attribute value 7883 * console.log(attrs.ngModel); 7884 * 7885 * // change the attribute 7886 * attrs.$set('ngModel', 'new value'); 7887 * 7888 * // observe changes to interpolated attribute 7889 * attrs.$observe('ngModel', function(value) { 7890 * console.log('ngModel has changed value to ' + value); 7891 * }); 7892 * } 7893 * ``` 7894 * 7895 * ## Example 7896 * 7897 * <div class="alert alert-warning"> 7898 * **Note**: Typically directives are registered with `module.directive`. The example below is 7899 * to illustrate how `$compile` works. 7900 * </div> 7901 * 7902 <example module="compileExample" name="compile"> 7903 <file name="index.html"> 7904 <script> 7905 angular.module('compileExample', [], function($compileProvider) { 7906 // configure new 'compile' directive by passing a directive 7907 // factory function. The factory function injects the '$compile' 7908 $compileProvider.directive('compile', function($compile) { 7909 // directive factory creates a link function 7910 return function(scope, element, attrs) { 7911 scope.$watch( 7912 function(scope) { 7913 // watch the 'compile' expression for changes 7914 return scope.$eval(attrs.compile); 7915 }, 7916 function(value) { 7917 // when the 'compile' expression changes 7918 // assign it into the current DOM 7919 element.html(value); 7920 7921 // compile the new DOM and link it to the current 7922 // scope. 7923 // NOTE: we only compile .childNodes so that 7924 // we don't get into infinite loop compiling ourselves 7925 $compile(element.contents())(scope); 7926 } 7927 ); 7928 }; 7929 }); 7930 }) 7931 .controller('GreeterController', ['$scope', function($scope) { 7932 $scope.name = 'Angular'; 7933 $scope.html = 'Hello {{name}}'; 7934 }]); 7935 </script> 7936 <div ng-controller="GreeterController"> 7937 <input ng-model="name"> <br/> 7938 <textarea ng-model="html"></textarea> <br/> 7939 <div compile="html"></div> 7940 </div> 7941 </file> 7942 <file name="protractor.js" type="protractor"> 7943 it('should auto compile', function() { 7944 var textarea = $('textarea'); 7945 var output = $('div[compile]'); 7946 // The initial state reads 'Hello Angular'. 7947 expect(output.getText()).toBe('Hello Angular'); 7948 textarea.clear(); 7949 textarea.sendKeys('{{name}}!'); 7950 expect(output.getText()).toBe('Angular!'); 7951 }); 7952 </file> 7953 </example> 7954 7955 * 7956 * 7957 * @param {string|DOMElement} element Element or HTML string to compile into a template function. 7958 * @param {function(angular.Scope, cloneAttachFn=)} transclude function available to directives - DEPRECATED. 7959 * 7960 * <div class="alert alert-danger"> 7961 * **Note:** Passing a `transclude` function to the $compile function is deprecated, as it 7962 * e.g. will not use the right outer scope. Please pass the transclude function as a 7963 * `parentBoundTranscludeFn` to the link function instead. 7964 * </div> 7965 * 7966 * @param {number} maxPriority only apply directives lower than given priority (Only effects the
7967 * root element(s), not their children) 7968 * @returns {function(scope, cloneAttachFn=, options=)} a link function which is used to bind template 7969 * (a DOM element/tree) to a scope. Where: 7970 * 7971 * * `scope` - A {@link ng.$rootScope.Scope Scope} to bind to. 7972 * * `cloneAttachFn` - If `cloneAttachFn` is provided, then the link function will clone the 7973 * `template` and call the `cloneAttachFn` function allowing the caller to attach the 7974 * cloned elements to the DOM document at the appropriate place. The `cloneAttachFn` is 7975 * called as: <br/> `cloneAttachFn(clonedElement, scope)` where: 7976 * 7977 * * `clonedElement` - is a clone of the original `element` passed into the compiler. 7978 * * `scope` - is the current scope with which the linking function is working with. 7979 * 7980 * * `options` - An optional object hash with linking options. If `options` is provided, then the following 7981 * keys may be used to control linking behavior: 7982 * 7983 * * `parentBoundTranscludeFn` - the transclude function made available to 7984 * directives; if given, it will be passed through to the link functions of 7985 * directives found in `element` during compilation. 7986 * * `transcludeControllers` - an object hash with keys that map controller names 7987 * to a hash with the key `instance`, which maps to the controller instance; 7988 * if given, it will make the controllers available to directives on the compileNode: 7989 * ``` 7990 * { 7991 * parent: { 7992 * instance: parentControllerInstance 7993 * } 7994 * } 7995 * ``` 7996 * * `futureParentElement` - defines the parent to which the `cloneAttachFn` will add 7997 * the cloned elements; only needed for transcludes that are allowed to contain non html 7998 * elements (e.g. SVG elements). See also the directive.controller property. 7999 * 8000 * Calling the linking function returns the element of the template. It is either the original 8001 * element passed in, or the clone of the element if the `cloneAttachFn` is provided. 8002 * 8003 * After linking the view is not updated until after a call to $digest which typically is done by 8004 * Angular automatically. 8005 * 8006 * If you need access to the bound view, there are two ways to do it: 8007 * 8008 * - If you are not asking the linking function to clone the template, create the DOM element(s) 8009 * before you send them to the compiler and keep this reference around. 8010 * ```js 8011 * var element = $compile('<p>{{total}}</p>')(scope); 8012 * ``` 8013 * 8014 * - if on the other hand, you need the element to be cloned, the view reference from the original 8015 * example would not point to the clone, but rather to the original template that was cloned. In 8016 * this case, you can access the clone via the cloneAttachFn: 8017 * ```js 8018 * var templateElement = angular.element('<p>{{total}}</p>'), 8019 * scope = ....; 8020 * 8021 * var clonedElement = $compile(templateElement)(scope, function(clonedElement, scope) { 8022 * //attach the clone to DOM document at the right place 8023 * }); 8024 * 8025 * //now we have reference to the cloned DOM via `clonedElement` 8026 * ``` 8027 * 8028 * 8029 * For information on how the compiler works, see the 8030 * {@link guide/compiler Angular HTML Compiler} section of the Developer Guide. 8031 * 8032 * @knownIssue 8033 * 8034 * ### Double Compilation 8035 * 8036 Double compilation occurs when an already compiled part of the DOM gets 8037 compiled again. This is an undesired effect and can lead to misbehaving directives, performance issues, 8038 and memory leaks. Refer to the Compiler Guide {@link guide/compiler#double-compilation-and-how-to-avoid-it 8039 section on double compilation} for an in-depth explanation and ways to avoid it. 8040 * 8041 */ 8042 8043var $compileMinErr = minErr('$compile'); 8044 8045function UNINITIALIZED_VALUE() {} 8046var _UNINITIALIZED_VALUE = new UNINITIALIZED_VALUE(); 8047 8048/** 8049 * @ngdoc provider 8050 * @name $compileProvider 8051 * 8052 * @description 8053 */
vendor: 15,345 bytes, lines 8054-8424
8054$CompileProvider.$inject = ['$provide', '$$sanitizeUriProvider']; 8055/** @this */ 8056function $CompileProvider($provide, $$sanitizeUriProvider) { 8057 var hasDirectives = {}, 8058 Suffix = 'Directive', 8059 COMMENT_DIRECTIVE_REGEXP = /^\s*directive:\s*([\w-]+)\s+(.*)$/, 8060 CLASS_DIRECTIVE_REGEXP = /(([\w-]+)(?::([^;]+))?;?)/, 8061 ALL_OR_NOTHING_ATTRS = makeMap('ngSrc,ngSrcset,src,srcset'), 8062 REQUIRE_PREFIX_REGEXP = /^(?:(\^\^?)?(\?)?(\^\^?)?)?/; 8063 8064 // Ref: http://developers.whatwg.org/webappapis.html#event-handler-idl-attributes 8065 // The assumption is that future DOM event attribute names will begin with 8066 // 'on' and be composed of only English letters. 8067 var EVENT_HANDLER_ATTR_REGEXP = /^(on[a-z]+|formaction)$/; 8068 var bindingCache = createMap(); 8069 8070 function parseIsolateBindings(scope, directiveName, isController) { 8071 var LOCAL_REGEXP = /^\s*([@&<]|=(\*?))(\??)\s*([\w$]*)\s*$/; 8072 8073 var bindings = createMap(); 8074 8075 forEach(scope, function(definition, scopeName) { 8076 if (definition in bindingCache) { 8077 bindings[scopeName] = bindingCache[definition]; 8078 return; 8079 } 8080 var match = definition.match(LOCAL_REGEXP); 8081 8082 if (!match) { 8083 throw $compileMinErr('iscp', 8084 'Invalid {3} for directive \'{0}\'.' + 8085 ' Definition: {... {1}: \'{2}\' ...}', 8086 directiveName, scopeName, definition, 8087 (isController ? 'controller bindings definition' : 8088 'isolate scope definition')); 8089 } 8090 8091 bindings[scopeName] = { 8092 mode: match[1][0], 8093 collection: match[2] === '*', 8094 optional: match[3] === '?', 8095 attrName: match[4] || scopeName 8096 }; 8097 if (match[4]) { 8098 bindingCache[definition] = bindings[scopeName]; 8099 } 8100 }); 8101 8102 return bindings; 8103 } 8104 8105 function parseDirectiveBindings(directive, directiveName) { 8106 var bindings = { 8107 isolateScope: null, 8108 bindToController: null 8109 }; 8110 if (isObject(directive.scope)) { 8111 if (directive.bindToController === true) { 8112 bindings.bindToController = parseIsolateBindings(directive.scope, 8113 directiveName, true); 8114 bindings.isolateScope = {}; 8115 } else { 8116 bindings.isolateScope = parseIsolateBindings(directive.scope, 8117 directiveName, false); 8118 } 8119 } 8120 if (isObject(directive.bindToController)) { 8121 bindings.bindToController = 8122 parseIsolateBindings(directive.bindToController, directiveName, true); 8123 } 8124 if (bindings.bindToController && !directive.controller) { 8125 // There is no controller 8126 throw $compileMinErr('noctrl', 8127 'Cannot bind to controller without directive \'{0}\'s controller.', 8128 directiveName); 8129 } 8130 return bindings; 8131 } 8132 8133 function assertValidDirectiveName(name) { 8134 var letter = name.charAt(0); 8135 if (!letter || letter !== lowercase(letter)) { 8136 throw $compileMinErr('baddir', 'Directive/Component name \'{0}\' is invalid. The first character must be a lowercase letter', name); 8137 } 8138 if (name !== name.trim()) { 8139 throw $compileMinErr('baddir', 8140 'Directive/Component name \'{0}\' is invalid. The name should not contain leading or trailing whitespaces', 8141 name); 8142 } 8143 } 8144 8145 function getDirectiveRequire(directive) { 8146 var require = directive.require || (directive.controller && directive.name); 8147 8148 if (!isArray(require) && isObject(require)) { 8149 forEach(require, function(value, key) { 8150 var match = value.match(REQUIRE_PREFIX_REGEXP); 8151 var name = value.substring(match[0].length); 8152 if (!name) require[key] = match[0] + key; 8153 }); 8154 } 8155 8156 return require; 8157 } 8158 8159 function getDirectiveRestrict(restrict, name) { 8160 if (restrict && !(isString(restrict) && /[EACM]/.test(restrict))) { 8161 throw $compileMinErr('badrestrict', 8162 'Restrict property \'{0}\' of directive \'{1}\' is invalid', 8163 restrict, 8164 name); 8165 } 8166 8167 return restrict || 'EA'; 8168 } 8169 8170 /** 8171 * @ngdoc method 8172 * @name $compileProvider#directive 8173 * @kind function 8174 * 8175 * @description 8176 * Register a new directive with the compiler. 8177 * 8178 * @param {string|Object} name Name of the directive in camel-case (i.e. <code>ngBind</code> which 8179 * will match as <code>ng-bind</code>), or an object map of directives where the keys are the 8180 * names and the values are the factories. 8181 * @param {Function|Array} directiveFactory An injectable directive factory function. See the 8182 * {@link guide/directive directive guide} and the {@link $compile compile API} for more info. 8183 * @returns {ng.$compileProvider} Self for chaining. 8184 */ 8185 this.directive = function registerDirective(name, directiveFactory) { 8186 assertArg(name, 'name'); 8187 assertNotHasOwnProperty(name, 'directive'); 8188 if (isString(name)) { 8189 assertValidDirectiveName(name); 8190 assertArg(directiveFactory, 'directiveFactory'); 8191 if (!hasDirectives.hasOwnProperty(name)) { 8192 hasDirectives[name] = []; 8193 $provide.factory(name + Suffix, ['$injector', '$exceptionHandler', 8194 function($injector, $exceptionHandler) { 8195 var directives = []; 8196 forEach(hasDirectives[name], function(directiveFactory, index) { 8197 try { 8198 var directive = $injector.invoke(directiveFactory); 8199 if (isFunction(directive)) { 8200 directive = { compile: valueFn(directive) }; 8201 } else if (!directive.compile && directive.link) { 8202 directive.compile = valueFn(directive.link); 8203 } 8204 directive.priority = directive.priority || 0; 8205 directive.index = index; 8206 directive.name = directive.name || name; 8207 directive.require = getDirectiveRequire(directive); 8208 directive.restrict = getDirectiveRestrict(directive.restrict, name); 8209 directive.$$moduleName = directiveFactory.$$moduleName; 8210 directives.push(directive); 8211 } catch (e) { 8212 $exceptionHandler(e); 8213 } 8214 }); 8215 return directives; 8216 }]); 8217 } 8218 hasDirectives[name].push(directiveFactory); 8219 } else { 8220 forEach(name, reverseParams(registerDirective)); 8221 } 8222 return this; 8223 }; 8224 8225 /** 8226 * @ngdoc method 8227 * @name $compileProvider#component 8228 * @module ng 8229 * @param {string|Object} name Name of the component in camelCase (i.e. `myComp` which will match `<my-comp>`), 8230 * or an object map of components where the keys are the names and the values are the component definition objects. 8231 * @param {Object} options Component definition object (a simplified 8232 * {@link ng.$compile#directive-definition-object directive definition object}), 8233 * with the following properties (all optional): 8234 * 8235 * - `controller` – `{(string|function()=}` – controller constructor function that should be 8236 * associated with newly created scope or the name of a {@link ng.$compile#-controller- 8237 * registered controller} if passed as a string. An empty `noop` function by default. 8238 * - `controllerAs` – `{string=}` – identifier name for to reference the controller in the component's scope. 8239 * If present, the controller will be published to scope under the `controllerAs` name. 8240 * If not present, this will default to be `$ctrl`. 8241 * - `template` – `{string=|function()=}` – html template as a string or a function that 8242 * returns an html template as a string which should be used as the contents of this component. 8243 * Empty string by default. 8244 * 8245 * If `template` is a function, then it is {@link auto.$injector#invoke injected} with 8246 * the following locals: 8247 * 8248 * - `$element` - Current element 8249 * - `$attrs` - Current attributes object for the element 8250 * 8251 * - `templateUrl` – `{string=|function()=}` – path or function that returns a path to an html 8252 * template that should be used as the contents of this component. 8253 * 8254 * If `templateUrl` is a function, then it is {@link auto.$injector#invoke injected} with 8255 * the following locals: 8256 * 8257 * - `$element` - Current element 8258 * - `$attrs` - Current attributes object for the element 8259 * 8260 * - `bindings` – `{object=}` – defines bindings between DOM attributes and component properties. 8261 * Component properties are always bound to the component controller and not to the scope. 8262 * See {@link ng.$compile#-bindtocontroller- `bindToController`}. 8263 * - `transclude` – `{boolean=}` – whether {@link $compile#transclusion content transclusion} is enabled. 8264 * Disabled by default. 8265 * - `require` - `{Object<string, string>=}` - requires the controllers of other directives and binds them to 8266 * this component's controller. The object keys specify the property names under which the required 8267 * controllers (object values) will be bound. See {@link ng.$compile#-require- `require`}. 8268 * - `$...` – additional properties to attach to the directive factory function and the controller 8269 * constructor function. (This is used by the component router to annotate) 8270 * 8271 * @returns {ng.$compileProvider} the compile provider itself, for chaining of function calls. 8272 * @description 8273 * Register a **component definition** with the compiler. This is a shorthand for registering a special 8274 * type of directive, which represents a self-contained UI component in your application. Such components 8275 * are always isolated (i.e. `scope: {}`) and are always restricted to elements (i.e. `restrict: 'E'`). 8276 * 8277 * Component definitions are very simple and do not require as much configuration as defining general 8278 * directives. Component definitions usually consist only of a template and a controller backing it. 8279 * 8280 * In order to make the definition easier, components enforce best practices like use of `controllerAs`, 8281 * `bindToController`. They always have **isolate scope** and are restricted to elements. 8282 * 8283 * Here are a few examples of how you would usually define components: 8284 * 8285 * ```js 8286 * var myMod = angular.module(...); 8287 * myMod.component('myComp', { 8288 * template: '<div>My name is {{$ctrl.name}}</div>', 8289 * controller: function() { 8290 * this.name = 'shahar'; 8291 * } 8292 * }); 8293 * 8294 * myMod.component('myComp', { 8295 * template: '<div>My name is {{$ctrl.name}}</div>', 8296 * bindings: {name: '@'} 8297 * }); 8298 * 8299 * myMod.component('myComp', { 8300 * templateUrl: 'views/my-comp.html', 8301 * controller: 'MyCtrl', 8302 * controllerAs: 'ctrl', 8303 * bindings: {name: '@'} 8304 * }); 8305 * 8306 * ``` 8307 * For more examples, and an in-depth guide, see the {@link guide/component component guide}. 8308 * 8309 * <br /> 8310 * See also {@link ng.$compileProvider#directive $compileProvider.directive()}. 8311 */ 8312 this.component = function registerComponent(name, options) { 8313 if (!isString(name)) { 8314 forEach(name, reverseParams(bind(this, registerComponent))); 8315 return this; 8316 } 8317 8318 var controller = options.controller || function() {}; 8319 8320 function factory($injector) { 8321 function makeInjectable(fn) { 8322 if (isFunction(fn) || isArray(fn)) { 8323 return /** @this */ function(tElement, tAttrs) { 8324 return $injector.invoke(fn, this, {$element: tElement, $attrs: tAttrs}); 8325 }; 8326 } else { 8327 return fn; 8328 } 8329 } 8330 8331 var template = (!options.template && !options.templateUrl ? '' : options.template); 8332 var ddo = { 8333 controller: controller, 8334 controllerAs: identifierForController(options.controller) || options.controllerAs || '$ctrl', 8335 template: makeInjectable(template), 8336 templateUrl: makeInjectable(options.templateUrl), 8337 transclude: options.transclude, 8338 scope: {}, 8339 bindToController: options.bindings || {}, 8340 restrict: 'E', 8341 require: options.require 8342 }; 8343 8344 // Copy annotations (starting with $) over to the DDO 8345 forEach(options, function(val, key) { 8346 if (key.charAt(0) === '$') ddo[key] = val; 8347 }); 8348 8349 return ddo; 8350 } 8351 8352 // TODO(pete) remove the following `forEach` before we release 1.6.0 8353 // The [email protected] looks for the annotations on the controller constructor 8354 // Nothing in Angular looks for annotations on the factory function but we can't remove 8355 // it from 1.5.x yet. 8356 8357 // Copy any annotation properties (starting with $) over to the factory and controller constructor functions 8358 // These could be used by libraries such as the new component router 8359 forEach(options, function(val, key) { 8360 if (key.charAt(0) === '$') { 8361 factory[key] = val; 8362 // Don't try to copy over annotations to named controller 8363 if (isFunction(controller)) controller[key] = val; 8364 } 8365 }); 8366 8367 factory.$inject = ['$injector']; 8368 8369 return this.directive(name, factory); 8370 }; 8371 8372 8373 /** 8374 * @ngdoc method 8375 * @name $compileProvider#aHrefSanitizationWhitelist 8376 * @kind function 8377 * 8378 * @description 8379 * Retrieves or overrides the default regular expression that is used for whitelisting of safe 8380 * urls during a[href] sanitization. 8381 * 8382 * The sanitization is a security measure aimed at preventing XSS attacks via html links. 8383 * 8384 * Any url about to be assigned to a[href] via data-binding is first normalized and turned into 8385 * an absolute url. Afterwards, the url is matched against the `aHrefSanitizationWhitelist` 8386 * regular expression. If a match is found, the original url is written into the dom. Otherwise, 8387 * the absolute url is prefixed with `'unsafe:'` string and only then is it written into the DOM. 8388 * 8389 * @param {RegExp=} regexp New regexp to whitelist urls with. 8390 * @returns {RegExp|ng.$compileProvider} Current RegExp if called without value or self for 8391 * chaining otherwise. 8392 */ 8393 this.aHrefSanitizationWhitelist = function(regexp) { 8394 if (isDefined(regexp)) { 8395 $$sanitizeUriProvider.aHrefSanitizationWhitelist(regexp); 8396 return this; 8397 } else { 8398 return $$sanitizeUriProvider.aHrefSanitizationWhitelist(); 8399 } 8400 }; 8401 8402 8403 /** 8404 * @ngdoc method 8405 * @name $compileProvider#imgSrcSanitizationWhitelist 8406 * @kind function 8407 * 8408 * @description 8409 * Retrieves or overrides the default regular expression that is used for whitelisting of safe 8410 * urls during img[src] sanitization. 8411 * 8412 * The sanitization is a security measure aimed at prevent XSS attacks via html links. 8413 * 8414 * Any url about to be assigned to img[src] via data-binding is first normalized and turned into 8415 * an absolute url. Afterwards, the url is matched against the `imgSrcSanitizationWhitelist` 8416 * regular expression. If a match is found, the original url is written into the dom. Otherwise, 8417 * the absolute url is prefixed with `'unsafe:'` string and only then is it written into the DOM. 8418 * 8419 * @param {RegExp=} regexp New regexp to whitelist urls with. 8420 * @returns {RegExp|ng.$compileProvider} Current RegExp if called without value or self for 8421 * chaining otherwise. 8422 */ 8423 this.imgSrcSanitizationWhitelist = function(regexp) { 8424 if (isDefined(regexp)) {
8425 $$sanitizeUriProvider.imgSrcSanitizationWhitelist(regexp); 8426 return this; 8427 } else { 8428 return $$sanitizeUriProvider.imgSrcSanitizationWhitelist(); 8429 } 8430 }; 8431 8432 /** 8433 * @ngdoc method 8434 * @name $compileProvider#debugInfoEnabled 8435 * 8436 * @param {boolean=} enabled update the debugInfoEnabled state if provided, otherwise just return the 8437 * current debugInfoEnabled state 8438 * @returns {*} current value if used as getter or itself (chaining) if used as setter 8439 * 8440 * @kind function 8441 * 8442 * @description 8443 * Call this method to enable/disable various debug runtime information in the compiler such as adding 8444 * binding information and a reference to the current scope on to DOM elements. 8445 * If enabled, the compiler will add the following to DOM elements that have been bound to the scope 8446 * * `ng-binding` CSS class 8447 * * `$binding` data property containing an array of the binding expressions 8448 * 8449 * You may want to disable this in production for a significant performance boost. See 8450 * {@link guide/production#disabling-debug-data Disabling Debug Data} for more. 8451 * 8452 * The default value is true. 8453 */ 8454 var debugInfoEnabled = true; 8455 this.debugInfoEnabled = function(enabled) { 8456 if (isDefined(enabled)) { 8457 debugInfoEnabled = enabled; 8458 return this; 8459 } 8460 return debugInfoEnabled; 8461 }; 8462 8463 /** 8464 * @ngdoc method 8465 * @name $compileProvider#preAssignBindingsEnabled 8466 * 8467 * @param {boolean=} enabled update the preAssignBindingsEnabled state if provided, otherwise just return the 8468 * current preAssignBindingsEnabled state 8469 * @returns {*} current value if used as getter or itself (chaining) if used as setter 8470 * 8471 * @kind function 8472 * 8473 * @description 8474 * Call this method to enable/disable whether directive controllers are assigned bindings before 8475 * calling the controller's constructor. 8476 * If enabled (true), the compiler assigns the value of each of the bindings to the 8477 * properties of the controller object before the constructor of this object is called. 8478 * 8479 * If disabled (false), the compiler calls the constructor first before assigning bindings. 8480 * 8481 * The default value is false. 8482 * 8483 * @deprecated 8484 * sinceVersion="1.6.0" 8485 * removeVersion="1.7.0" 8486 * 8487 * This method and the option to assign the bindings before calling the controller's constructor 8488 * will be removed in v1.7.0. 8489 */ 8490 var preAssignBindingsEnabled = false; 8491 this.preAssignBindingsEnabled = function(enabled) { 8492 if (isDefined(enabled)) { 8493 preAssignBindingsEnabled = enabled; 8494 return this; 8495 } 8496 return preAssignBindingsEnabled; 8497 }; 8498 8499 /** 8500 * @ngdoc method 8501 * @name $compileProvider#strictComponentBindingsEnabled 8502 * 8503 * @param {boolean=} enabled update the strictComponentBindingsEnabled state if provided, otherwise just return the 8504 * current strictComponentBindingsEnabled state 8505 * @returns {*} current value if used as getter or itself (chaining) if used as setter 8506 * 8507 * @kind function 8508 * 8509 * @description 8510 * Call this method to enable/disable strict component bindings check. If enabled, the compiler will enforce that 8511 * for all bindings of a component that are not set as optional with `?`, an attribute needs to be provided 8512 * on the component's HTML tag. 8513 * 8514 * The default value is false. 8515 */ 8516 var strictComponentBindingsEnabled = false; 8517 this.strictComponentBindingsEnabled = function(enabled) { 8518 if (isDefined(enabled)) { 8519 strictComponentBindingsEnabled = enabled; 8520 return this; 8521 } 8522 return strictComponentBindingsEnabled; 8523 }; 8524 8525 var TTL = 10; 8526 /** 8527 * @ngdoc method 8528 * @name $compileProvider#onChangesTtl 8529 * @description 8530 * 8531 * Sets the number of times `$onChanges` hooks can trigger new changes before giving up and 8532 * assuming that the model is unstable. 8533 * 8534 * The current default is 10 iterations. 8535 * 8536 * In complex applications it's possible that dependencies between `$onChanges` hooks and bindings will result 8537 * in several iterations of calls to these hooks. However if an application needs more than the default 10 8538 * iterations to stabilize then you should investigate what is causing the model to continuously change during 8539 * the `$onChanges` hook execution. 8540 * 8541 * Increasing the TTL could have performance implications, so you should not change it without proper justification. 8542 * 8543 * @param {number} limit The number of `$onChanges` hook iterations. 8544 * @returns {number|object} the current limit (or `this` if called as a setter for chaining) 8545 */ 8546 this.onChangesTtl = function(value) { 8547 if (arguments.length) { 8548 TTL = value; 8549 return this; 8550 } 8551 return TTL; 8552 }; 8553 8554 var commentDirectivesEnabledConfig = true; 8555 /** 8556 * @ngdoc method 8557 * @name $compileProvider#commentDirectivesEnabled 8558 * @description 8559 * 8560 * It indicates to the compiler 8561 * whether or not directives on comments should be compiled. 8562 * Defaults to `true`. 8563 *
8564 * Calling this function with false disables the compilation of directives 8565 * on comments for the whole application. 8566 * This results in a compilation performance gain, 8567 * as the compiler doesn't have to check comments when looking for directives. 8568 * This should however only be used if you are sure that no comment directives are used in 8569 * the application (including any 3rd party directives). 8570 * 8571 * @param {boolean} enabled `false` if the compiler may ignore directives on comments 8572 * @returns {boolean|object} the current value (or `this` if called as a setter for chaining) 8573 */ 8574 this.commentDirectivesEnabled = function(value) { 8575 if (arguments.length) { 8576 commentDirectivesEnabledConfig = value; 8577 return this; 8578 } 8579 return commentDirectivesEnabledConfig; 8580 }; 8581 8582 8583 var cssClassDirectivesEnabledConfig = true; 8584 /** 8585 * @ngdoc method 8586 * @name $compileProvider#cssClassDirectivesEnabled 8587 * @description 8588 * 8589 * It indicates to the compiler 8590 * whether or not directives on element classes should be compiled. 8591 * Defaults to `true`. 8592 * 8593 * Calling this function with false disables the compilation of directives 8594 * on element classes for the whole application. 8595 * This results in a compilation performance gain, 8596 * as the compiler doesn't have to check element classes when looking for directives. 8597 * This should however only be used if you are sure that no class directives are used in 8598 * the application (including any 3rd party directives). 8599 * 8600 * @param {boolean} enabled `false` if the compiler may ignore directives on element classes 8601 * @returns {boolean|object} the current value (or `this` if called as a setter for chaining) 8602 */ 8603 this.cssClassDirectivesEnabled = function(value) { 8604 if (arguments.length) { 8605 cssClassDirectivesEnabledConfig = value; 8606 return this; 8607 } 8608 return cssClassDirectivesEnabledConfig; 8609 }; 8610 8611 this.$get = [ 8612 '$injector', '$interpolate', '$exceptionHandler', '$templateRequest', '$parse', 8613 '$controller', '$rootScope', '$sce', '$animate', '$$sanitizeUri', 8614 function($injector, $interpolate, $exceptionHandler, $templateRequest, $parse, 8615 $controller, $rootScope, $sce, $animate, $$sanitizeUri) { 8616 8617 var SIMPLE_ATTR_NAME = /^\w/; 8618 var specialAttrHolder = window.document.createElement('div'); 8619 8620 8621 var commentDirectivesEnabled = commentDirectivesEnabledConfig; 8622 var cssClassDirectivesEnabled = cssClassDirectivesEnabledConfig; 8623 8624 8625 var onChangesTtl = TTL; 8626 // The onChanges hooks should all be run together in a single digest 8627 // When changes occur, the call to trigger their hooks will be added to this queue 8628 var onChangesQueue; 8629 8630 // This function is called in a $$postDigest to trigger all the onChanges hooks in a single digest 8631 function flushOnChangesQueue() { 8632 try { 8633 if (!(--onChangesTtl)) { 8634 // We have hit the TTL limit so reset everything 8635 onChangesQueue = undefined; 8636 throw $compileMinErr('infchng', '{0} $onChanges() iterations reached. Aborting!\n', TTL); 8637 } 8638 // We must run this hook in an apply since the $$postDigest runs outside apply 8639 $rootScope.$apply(function() { 8640 var errors = []; 8641 for (var i = 0, ii = onChangesQueue.length; i < ii; ++i) { 8642 try { 8643 onChangesQueue[i](); 8644 } catch (e) { 8645 errors.push(e); 8646 } 8647 } 8648 // Reset the queue to trigger a new schedule next time there is a change 8649 onChangesQueue = undefined; 8650 if (errors.length) { 8651 throw errors; 8652 } 8653 }); 8654 } finally { 8655 onChangesTtl++; 8656 } 8657 } 8658 8659 8660 function Attributes(element, attributesToCopy) { 8661 if (attributesToCopy) { 8662 var keys = Object.keys(attributesToCopy); 8663 var i, l, key; 8664 8665 for (i = 0, l = keys.length; i < l; i++) { 8666 key = keys[i]; 8667 this[key] = attributesToCopy[key]; 8668 } 8669 } else { 8670 this.$attr = {}; 8671 } 8672 8673 this.$$element = element; 8674 } 8675 8676 Attributes.prototype = { 8677 /** 8678 * @ngdoc method 8679 * @name $compile.directive.Attributes#$normalize 8680 * @kind function 8681 *
8682 * @description 8683 * Converts an attribute name (e.g. dash/colon/underscore-delimited string, optionally prefixed with `x-` or 8684 * `data-`) to its normalized, camelCase form. 8685 * 8686 * Also there is special case for Moz prefix starting with upper case letter. 8687 * 8688 * For further information check out the guide on {@link guide/directive#matching-directives Matching Directives} 8689 * 8690 * @param {string} name Name to normalize 8691 */ 8692 $normalize: directiveNormalize, 8693 8694 8695 /** 8696 * @ngdoc method 8697 * @name $compile.directive.Attributes#$addClass 8698 * @kind function 8699 * 8700 * @description 8701 * Adds the CSS class value specified by the classVal parameter to the element. If animations 8702 * are enabled then an animation will be triggered for the class addition. 8703 * 8704 * @param {string} classVal The className value that will be added to the element 8705 */ 8706 $addClass: function(classVal) { 8707 if (classVal && classVal.length > 0) { 8708 $animate.addClass(this.$$element, classVal); 8709 } 8710 }, 8711 8712 /** 8713 * @ngdoc method 8714 * @name $compile.directive.Attributes#$removeClass 8715 * @kind function 8716 * 8717 * @description 8718 * Removes the CSS class value specified by the classVal parameter from the element. If 8719 * animations are enabled then an animation will be triggered for the class removal. 8720 * 8721 * @param {string} classVal The className value that will be removed from the element 8722 */ 8723 $removeClass: function(classVal) { 8724 if (classVal && classVal.length > 0) { 8725 $animate.removeClass(this.$$element, classVal); 8726 } 8727 }, 8728 8729 /** 8730 * @ngdoc method 8731 * @name $compile.directive.Attributes#$updateClass 8732 * @kind function 8733 * 8734 * @description 8735 * Adds and removes the appropriate CSS class values to the element based on the difference 8736 * between the new and old CSS class values (specified as newClasses and oldClasses). 8737 * 8738 * @param {string} newClasses The current CSS className value 8739 * @param {string} oldClasses The former CSS className value 8740 */ 8741 $updateClass: function(newClasses, oldClasses) { 8742 var toAdd = tokenDifference(newClasses, oldClasses); 8743 if (toAdd && toAdd.length) { 8744 $animate.addClass(this.$$element, toAdd); 8745 } 8746 8747 var toRemove = tokenDifference(oldClasses, newClasses); 8748 if (toRemove && toRemove.length) { 8749 $animate.removeClass(this.$$element, toRemove); 8750 } 8751 }, 8752 8753 /** 8754 * Set a normalized attribute on the element in a way such that all directives 8755 * can share the attribute. This function properly handles boolean attributes. 8756 * @param {string} key Normalized key. (ie ngAttribute) 8757 * @param {string|boolean} value The value to set. If `null` attribute will be deleted. 8758 * @param {boolean=} writeAttr If false, does not write the value to DOM element attribute. 8759 * Defaults to true. 8760 * @param {string=} attrName Optional none normalized name. Defaults to key. 8761 */ 8762 $set: function(key, value, writeAttr, attrName) { 8763 // TODO: decide whether or not to throw an error if "class" 8764 //is set through this function since it may cause $updateClass to 8765 //become unstable. 8766 8767 var node = this.$$element[0], 8768 booleanKey = getBooleanAttrName(node, key), 8769 aliasedKey = getAliasedAttrName(key), 8770 observer = key, 8771 nodeName; 8772 8773 if (booleanKey) { 8774 this.$$element.prop(key, value); 8775 attrName = booleanKey; 8776 } else if (aliasedKey) { 8777 this[aliasedKey] = value; 8778 observer = aliasedKey; 8779 } 8780 8781 this[key] = value; 8782 8783 // translate normalized key to actual key 8784 if (attrName) { 8785 this.$attr[key] = attrName; 8786 } else { 8787 attrName = this.$attr[key]; 8788 if (!attrName) { 8789 this.$attr[key] = attrName = snake_case(key, '-'); 8790 } 8791 } 8792 8793 nodeName = nodeName_(this.$$element); 8794 8795 if ((nodeName === 'a' && (key === 'href' || key === 'xlinkHref')) || 8796 (nodeName === 'img' && key === 'src')) { 8797 // sanitize a[href] and img[src] values 8798 this[key] = value = $$sanitizeUri(value, key === 'src'); 8799 } else if (nodeName === 'img' && key === 'srcset' && isDefined(value)) { 8800 // sanitize img[srcset] values 8801 var result = ''; 8802
vendor: 8,587 bytes, lines 8803-9020
8803 // first check if there are spaces because it's not the same pattern 8804 var trimmedSrcset = trim(value); 8805 // ( 999x ,| 999w ,| ,|, ) 8806 var srcPattern = /(\s+\d+x\s*,|\s+\d+w\s*,|\s+,|,\s+)/; 8807 var pattern = /\s/.test(trimmedSrcset) ? srcPattern : /(,)/; 8808 8809 // split srcset into tuple of uri and descriptor except for the last item 8810 var rawUris = trimmedSrcset.split(pattern); 8811 8812 // for each tuples 8813 var nbrUrisWith2parts = Math.floor(rawUris.length / 2); 8814 for (var i = 0; i < nbrUrisWith2parts; i++) { 8815 var innerIdx = i * 2; 8816 // sanitize the uri 8817 result += $$sanitizeUri(trim(rawUris[innerIdx]), true); 8818 // add the descriptor 8819 result += (' ' + trim(rawUris[innerIdx + 1])); 8820 } 8821 8822 // split the last item into uri and descriptor 8823 var lastTuple = trim(rawUris[i * 2]).split(/\s/); 8824 8825 // sanitize the last uri 8826 result += $$sanitizeUri(trim(lastTuple[0]), true); 8827 8828 // and add the last descriptor if any 8829 if (lastTuple.length === 2) { 8830 result += (' ' + trim(lastTuple[1])); 8831 } 8832 this[key] = value = result; 8833 } 8834 8835 if (writeAttr !== false) { 8836 if (value === null || isUndefined(value)) { 8837 this.$$element.removeAttr(attrName); 8838 } else { 8839 if (SIMPLE_ATTR_NAME.test(attrName)) { 8840 this.$$element.attr(attrName, value); 8841 } else { 8842 setSpecialAttr(this.$$element[0], attrName, value); 8843 } 8844 } 8845 } 8846 8847 // fire observers 8848 var $$observers = this.$$observers; 8849 if ($$observers) { 8850 forEach($$observers[observer], function(fn) { 8851 try { 8852 fn(value); 8853 } catch (e) { 8854 $exceptionHandler(e); 8855 } 8856 }); 8857 } 8858 }, 8859 8860 8861 /** 8862 * @ngdoc method 8863 * @name $compile.directive.Attributes#$observe 8864 * @kind function 8865 * 8866 * @description 8867 * Observes an interpolated attribute. 8868 * 8869 * The observer function will be invoked once during the next `$digest` following 8870 * compilation. The observer is then invoked whenever the interpolated value 8871 * changes. 8872 * 8873 * @param {string} key Normalized key. (ie ngAttribute) . 8874 * @param {function(interpolatedValue)} fn Function that will be called whenever 8875 the interpolated value of the attribute changes. 8876 * See the {@link guide/interpolation#how-text-and-attribute-bindings-work Interpolation 8877 * guide} for more info. 8878 * @returns {function()} Returns a deregistration function for this observer. 8879 */ 8880 $observe: function(key, fn) { 8881 var attrs = this, 8882 $$observers = (attrs.$$observers || (attrs.$$observers = createMap())), 8883 listeners = ($$observers[key] || ($$observers[key] = [])); 8884 8885 listeners.push(fn); 8886 $rootScope.$evalAsync(function() { 8887 if (!listeners.$$inter && attrs.hasOwnProperty(key) && !isUndefined(attrs[key])) { 8888 // no one registered attribute interpolation function, so lets call it manually 8889 fn(attrs[key]); 8890 } 8891 }); 8892 8893 return function() { 8894 arrayRemove(listeners, fn); 8895 }; 8896 } 8897 }; 8898 8899 function setSpecialAttr(element, attrName, value) { 8900 // Attributes names that do not start with letters (such as `(click)`) cannot be set using `setAttribute` 8901 // so we have to jump through some hoops to get such an attribute 8902 // https://github.com/angular/angular.js/pull/13318 8903 specialAttrHolder.innerHTML = '<span ' + attrName + '>'; 8904 var attributes = specialAttrHolder.firstChild.attributes; 8905 var attribute = attributes[0]; 8906 // We have to remove the attribute from its container element before we can add it to the destination element 8907 attributes.removeNamedItem(attribute.name); 8908 attribute.value = value; 8909 element.attributes.setNamedItem(attribute); 8910 } 8911 8912 function safeAddClass($element, className) { 8913 try { 8914 $element.addClass(className); 8915 } catch (e) { 8916 // ignore, since it means that we are trying to set class on 8917 // SVG element, where class name is read-only. 8918 } 8919 } 8920 8921 8922 var startSymbol = $interpolate.startSymbol(), 8923 endSymbol = $interpolate.endSymbol(), 8924 denormalizeTemplate = (startSymbol === '{{' && endSymbol === '}}') 8925 ? identity 8926 : function denormalizeTemplate(template) { 8927 return template.replace(/\{\{/g, startSymbol).replace(/}}/g, endSymbol); 8928 }, 8929 NG_ATTR_BINDING = /^ngAttr[A-Z]/; 8930 var MULTI_ELEMENT_DIR_RE = /^(.+)Start$/; 8931 8932 compile.$$addBindingInfo = debugInfoEnabled ? function $$addBindingInfo($element, binding) { 8933 var bindings = $element.data('$binding') || []; 8934 8935 if (isArray(binding)) { 8936 bindings = bindings.concat(binding); 8937 } else { 8938 bindings.push(binding); 8939 } 8940 8941 $element.data('$binding', bindings); 8942 } : noop; 8943 8944 compile.$$addBindingClass = debugInfoEnabled ? function $$addBindingClass($element) { 8945 safeAddClass($element, 'ng-binding'); 8946 } : noop; 8947 8948 compile.$$addScopeInfo = debugInfoEnabled ? function $$addScopeInfo($element, scope, isolated, noTemplate) { 8949 var dataName = isolated ? (noTemplate ? '$isolateScopeNoTemplate' : '$isolateScope') : '$scope'; 8950 $element.data(dataName, scope); 8951 } : noop; 8952 8953 compile.$$addScopeClass = debugInfoEnabled ? function $$addScopeClass($element, isolated) { 8954 safeAddClass($element, isolated ? 'ng-isolate-scope' : 'ng-scope'); 8955 } : noop; 8956 8957 compile.$$createComment = function(directiveName, comment) { 8958 var content = ''; 8959 if (debugInfoEnabled) { 8960 content = ' ' + (directiveName || '') + ': '; 8961 if (comment) content += comment + ' '; 8962 } 8963 return window.document.createComment(content); 8964 }; 8965 8966 return compile; 8967 8968 //================================ 8969 8970 function compile($compileNodes, transcludeFn, maxPriority, ignoreDirective, 8971 previousCompileContext) { 8972 if (!($compileNodes instanceof jqLite)) { 8973 // jquery always rewraps, whereas we need to preserve the original selector so that we can 8974 // modify it. 8975 $compileNodes = jqLite($compileNodes); 8976 } 8977 var compositeLinkFn = 8978 compileNodes($compileNodes, transcludeFn, $compileNodes, 8979 maxPriority, ignoreDirective, previousCompileContext); 8980 compile.$$addScopeClass($compileNodes); 8981 var namespace = null; 8982 return function publicLinkFn(scope, cloneConnectFn, options) { 8983 if (!$compileNodes) { 8984 throw $compileMinErr('multilink', 'This element has already been linked.'); 8985 } 8986 assertArg(scope, 'scope'); 8987 8988 if (previousCompileContext && previousCompileContext.needsNewScope) { 8989 // A parent directive did a replace and a directive on this element asked 8990 // for transclusion, which caused us to lose a layer of element on which 8991 // we could hold the new transclusion scope, so we will create it manually 8992 // here. 8993 scope = scope.$parent.$new(); 8994 } 8995 8996 options = options || {}; 8997 var parentBoundTranscludeFn = options.parentBoundTranscludeFn, 8998 transcludeControllers = options.transcludeControllers, 8999 futureParentElement = options.futureParentElement; 9000 9001 // When `parentBoundTranscludeFn` is passed, it is a 9002 // `controllersBoundTransclude` function (it was previously passed 9003 // as `transclude` to directive.link) so we must unwrap it to get 9004 // its `boundTranscludeFn` 9005 if (parentBoundTranscludeFn && parentBoundTranscludeFn.$$boundTransclude) { 9006 parentBoundTranscludeFn = parentBoundTranscludeFn.$$boundTransclude; 9007 } 9008 9009 if (!namespace) { 9010 namespace = detectNamespaceForChildElements(futureParentElement); 9011 } 9012 var $linkNode; 9013 if (namespace !== 'html') { 9014 // When using a directive with replace:true and templateUrl the $compileNodes 9015 // (or a child element inside of them) 9016 // might change, so we need to recreate the namespace adapted compileNodes 9017 // for call to the link function. 9018 // Note: This will already clone the nodes... 9019 $linkNode = jqLite( 9020 wrapTemplate(namespace, jqLite('<
vendor: 9,507 bytes, lines 9020-9265
9020div>').append($compileNodes).html()) 9021 ); 9022 } else if (cloneConnectFn) { 9023 // important!!: we must call our jqLite.clone() since the jQuery one is trying to be smart 9024 // and sometimes changes the structure of the DOM. 9025 $linkNode = JQLitePrototype.clone.call($compileNodes); 9026 } else { 9027 $linkNode = $compileNodes; 9028 } 9029 9030 if (transcludeControllers) { 9031 for (var controllerName in transcludeControllers) { 9032 $linkNode.data('$' + controllerName + 'Controller', transcludeControllers[controllerName].instance); 9033 } 9034 } 9035 9036 compile.$$addScopeInfo($linkNode, scope); 9037 9038 if (cloneConnectFn) cloneConnectFn($linkNode, scope); 9039 if (compositeLinkFn) compositeLinkFn(scope, $linkNode, $linkNode, parentBoundTranscludeFn); 9040 9041 if (!cloneConnectFn) { 9042 $compileNodes = compositeLinkFn = null; 9043 } 9044 return $linkNode; 9045 }; 9046 } 9047 9048 function detectNamespaceForChildElements(parentElement) { 9049 // TODO: Make this detect MathML as well... 9050 var node = parentElement && parentElement[0]; 9051 if (!node) { 9052 return 'html'; 9053 } else { 9054 return nodeName_(node) !== 'foreignobject' && toString.call(node).match(/SVG/) ? 'svg' : 'html'; 9055 } 9056 } 9057 9058 /** 9059 * Compile function matches each node in nodeList against the directives. Once all directives 9060 * for a particular node are collected their compile functions are executed. The compile 9061 * functions return values - the linking functions - are combined into a composite linking 9062 * function, which is the a linking function for the node. 9063 * 9064 * @param {NodeList} nodeList an array of nodes or NodeList to compile 9065 * @param {function(angular.Scope, cloneAttachFn=)} transcludeFn A linking function, where the 9066 * scope argument is auto-generated to the new child of the transcluded parent scope. 9067 * @param {DOMElement=} $rootElement If the nodeList is the root of the compilation tree then 9068 * the rootElement must be set the jqLite collection of the compile root. This is 9069 * needed so that the jqLite collection items can be replaced with widgets. 9070 * @param {number=} maxPriority Max directive priority. 9071 * @returns {Function} A composite linking function of all of the matched directives or null. 9072 */ 9073 function compileNodes(nodeList, transcludeFn, $rootElement, maxPriority, ignoreDirective, 9074 previousCompileContext) { 9075 var linkFns = [], 9076 // `nodeList` can be either an element's `.childNodes` (live NodeList) 9077 // or a jqLite/jQuery collection or an array 9078 notLiveList = isArray(nodeList) || (nodeList instanceof jqLite), 9079 attrs, directives, nodeLinkFn, childNodes, childLinkFn, linkFnFound, nodeLinkFnFound; 9080 9081 9082 for (var i = 0; i < nodeList.length; i++) { 9083 attrs = new Attributes(); 9084 9085 // Support: IE 11 only 9086 // Workaround for #11781 and #14924 9087 if (msie === 11) { 9088 mergeConsecutiveTextNodes(nodeList, i, notLiveList); 9089 } 9090 9091 // We must always refer to `nodeList[i]` hereafter, 9092 // since the nodes can be replaced underneath us. 9093 directives = collectDirectives(nodeList[i], [], attrs, i === 0 ? maxPriority : undefined, 9094 ignoreDirective); 9095 9096 nodeLinkFn = (directives.length) 9097 ? applyDirectivesToNode(directives, nodeList[i], attrs, transcludeFn, $rootElement, 9098 null, [], [], previousCompileContext) 9099 : null; 9100 9101 if (nodeLinkFn && nodeLinkFn.scope) { 9102 compile.$$addScopeClass(attrs.$$element); 9103 } 9104 9105 childLinkFn = (nodeLinkFn && nodeLinkFn.terminal || 9106 !(childNodes = nodeList[i].childNodes) || 9107 !childNodes.length) 9108 ? null 9109 : compileNodes(childNodes, 9110 nodeLinkFn ? ( 9111 (nodeLinkFn.transcludeOnThisElement || !nodeLinkFn.templateOnThisElement) 9112 && nodeLinkFn.transclude) : transcludeFn); 9113 9114 if (nodeLinkFn || childLinkFn) { 9115 linkFns.push(i, nodeLinkFn, childLinkFn); 9116 linkFnFound = true; 9117 nodeLinkFnFound = nodeLinkFnFound || nodeLinkFn; 9118 } 9119 9120 //use the previous context only for the first element in the virtual group 9121 previousCompileContext = null; 9122 } 9123 9124 // return a linking function if we have found anything, null otherwise 9125 return linkFnFound ? compositeLinkFn : null; 9126 9127 function compositeLinkFn(scope, nodeList, $rootElement, parentBoundTranscludeFn) { 9128 var nodeLinkFn, childLinkFn, node, childScope, i, ii, idx, childBoundTranscludeFn; 9129 var stableNodeList; 9130 9131 9132 if (nodeLinkFnFound) { 9133 // copy nodeList so that if a nodeLinkFn removes or adds an element at this DOM level our 9134 // offsets don't get screwed up 9135 var nodeListLength = nodeList.length; 9136 stableNodeList = new Array(nodeListLength); 9137 9138 // create a sparse array by only copying the elements which have a linkFn 9139 for (i = 0; i < linkFns.length; i += 3) { 9140 idx = linkFns[i]; 9141 stableNodeList[idx] = nodeList[idx]; 9142 } 9143 } else { 9144 stableNodeList = nodeList; 9145 } 9146 9147 for (i = 0, ii = linkFns.length; i < ii;) { 9148 node = stableNodeList[linkFns[i++]]; 9149 nodeLinkFn = linkFns[i++]; 9150 childLinkFn = linkFns[i++]; 9151 9152 if (nodeLinkFn) { 9153 if (nodeLinkFn.scope) { 9154 childScope = scope.$new(); 9155 compile.$$addScopeInfo(jqLite(node), childScope); 9156 } else { 9157 childScope = scope; 9158 } 9159 9160 if (nodeLinkFn.transcludeOnThisElement) { 9161 childBoundTranscludeFn = createBoundTranscludeFn( 9162 scope, nodeLinkFn.transclude, parentBoundTranscludeFn); 9163 9164 } else if (!nodeLinkFn.templateOnThisElement && parentBoundTranscludeFn) { 9165 childBoundTranscludeFn = parentBoundTranscludeFn; 9166 9167 } else if (!parentBoundTranscludeFn && transcludeFn) { 9168 childBoundTranscludeFn = createBoundTranscludeFn(scope, transcludeFn); 9169 9170 } else { 9171 childBoundTranscludeFn = null; 9172 } 9173 9174 nodeLinkFn(childLinkFn, childScope, node, $rootElement, childBoundTranscludeFn); 9175 9176 } else if (childLinkFn) { 9177 childLinkFn(scope, node.childNodes, undefined, parentBoundTranscludeFn); 9178 } 9179 } 9180 } 9181 } 9182 9183 function mergeConsecutiveTextNodes(nodeList, idx, notLiveList) { 9184 var node = nodeList[idx]; 9185 var parent = node.parentNode; 9186 var sibling; 9187 9188 if (node.nodeType !== NODE_TYPE_TEXT) { 9189 return; 9190 } 9191 9192 while (true) { 9193 sibling = parent ? node.nextSibling : nodeList[idx + 1]; 9194 if (!sibling || sibling.nodeType !== NODE_TYPE_TEXT) { 9195 break; 9196 } 9197 9198 node.nodeValue = node.nodeValue + sibling.nodeValue; 9199 9200 if (sibling.parentNode) { 9201 sibling.parentNode.removeChild(sibling); 9202 } 9203 if (notLiveList && sibling === nodeList[idx + 1]) { 9204 nodeList.splice(idx + 1, 1); 9205 } 9206 } 9207 } 9208 9209 function createBoundTranscludeFn(scope, transcludeFn, previousBoundTranscludeFn) { 9210 function boundTranscludeFn(transcludedScope, cloneFn, controllers, futureParentElement, containingScope) { 9211 9212 if (!transcludedScope) { 9213 transcludedScope = scope.$new(false, containingScope); 9214 transcludedScope.$$transcluded = true; 9215 } 9216 9217 return transcludeFn(transcludedScope, cloneFn, { 9218 parentBoundTranscludeFn: previousBoundTranscludeFn, 9219 transcludeControllers: controllers, 9220 futureParentElement: futureParentElement 9221 }); 9222 } 9223 9224 // We need to attach the transclusion slots onto the `boundTranscludeFn` 9225 // so that they are available inside the `controllersBoundTransclude` function 9226 var boundSlots = boundTranscludeFn.$$slots = createMap(); 9227 for (var slotName in transcludeFn.$$slots) { 9228 if (transcludeFn.$$slots[slotName]) { 9229 boundSlots[slotName] = createBoundTranscludeFn(scope, transcludeFn.$$slots[slotName], previousBoundTranscludeFn); 9230 } else { 9231 boundSlots[slotName] = null; 9232 } 9233 } 9234 9235 return boundTranscludeFn; 9236 } 9237 9238 /** 9239 * Looks for directives on the given node and adds them to the directive collection which is 9240 * sorted. 9241 * 9242 * @param node Node to search. 9243 * @param directives An array to which the directives are added to. This array is sorted before 9244 * the function returns. 9245 * @param attrs The shared attrs object which is used to populate the normalized attributes. 9246 * @param {number=} maxPriority Max directive priority. 9247 */ 9248 function collectDirectives(node, directives, attrs, maxPriority, ignoreDirective) { 9249 var nodeType = node.nodeType, 9250 attrsMap = attrs.$attr, 9251 match, 9252 nodeName, 9253 className; 9254 9255 switch (nodeType) { 9256 case NODE_TYPE_ELEMENT: /* Element */ 9257 9258 nodeName = nodeName_(node); 9259 9260 // use the node name: <directive> 9261 addDirective(directives, 9262 directiveNormalize(nodeName), 'E', maxPriority, ignoreDirective); 9263 9264 // iterate over the attributes 9265 for (var attr, name, nName,
9265ngAttrName, value, isNgAttr, nAttrs = node.attributes, 9266 j = 0, jj = nAttrs && nAttrs.length; j < jj; j++) { 9267 var attrStartName = false;
vendor: 13,392 bytes, lines 9268-9573
9268 var attrEndName = false; 9269 9270 attr = nAttrs[j]; 9271 name = attr.name; 9272 value = attr.value; 9273 9274 // support ngAttr attribute binding 9275 ngAttrName = directiveNormalize(name); 9276 isNgAttr = NG_ATTR_BINDING.test(ngAttrName); 9277 if (isNgAttr) { 9278 name = name.replace(PREFIX_REGEXP, '') 9279 .substr(8).replace(/_(.)/g, function(match, letter) { 9280 return letter.toUpperCase(); 9281 }); 9282 } 9283 9284 var multiElementMatch = ngAttrName.match(MULTI_ELEMENT_DIR_RE); 9285 if (multiElementMatch && directiveIsMultiElement(multiElementMatch[1])) { 9286 attrStartName = name; 9287 attrEndName = name.substr(0, name.length - 5) + 'end'; 9288 name = name.substr(0, name.length - 6); 9289 } 9290 9291 nName = directiveNormalize(name.toLowerCase()); 9292 attrsMap[nName] = name; 9293 if (isNgAttr || !attrs.hasOwnProperty(nName)) { 9294 attrs[nName] = value; 9295 if (getBooleanAttrName(node, nName)) { 9296 attrs[nName] = true; // presence means true 9297 } 9298 } 9299 addAttrInterpolateDirective(node, directives, value, nName, isNgAttr); 9300 addDirective(directives, nName, 'A', maxPriority, ignoreDirective, attrStartName, 9301 attrEndName); 9302 } 9303 9304 if (nodeName === 'input' && node.getAttribute('type') === 'hidden') { 9305 // Hidden input elements can have strange behaviour when navigating back to the page 9306 // This tells the browser not to try to cache and reinstate previous values 9307 node.setAttribute('autocomplete', 'off'); 9308 } 9309 9310 // use class as directive 9311 if (!cssClassDirectivesEnabled) break; 9312 className = node.className; 9313 if (isObject(className)) { 9314 // Maybe SVGAnimatedString 9315 className = className.animVal; 9316 } 9317 if (isString(className) && className !== '') { 9318 while ((match = CLASS_DIRECTIVE_REGEXP.exec(className))) { 9319 nName = directiveNormalize(match[2]); 9320 if (addDirective(directives, nName, 'C', maxPriority, ignoreDirective)) { 9321 attrs[nName] = trim(match[3]); 9322 } 9323 className = className.substr(match.index + match[0].length); 9324 } 9325 } 9326 break; 9327 case NODE_TYPE_TEXT: /* Text Node */ 9328 addTextInterpolateDirective(directives, node.nodeValue); 9329 break; 9330 case NODE_TYPE_COMMENT: /* Comment */ 9331 if (!commentDirectivesEnabled) break; 9332 collectCommentDirectives(node, directives, attrs, maxPriority, ignoreDirective); 9333 break; 9334 } 9335 9336 directives.sort(byPriority); 9337 return directives; 9338 } 9339 9340 function collectCommentDirectives(node, directives, attrs, maxPriority, ignoreDirective) { 9341 // function created because of performance, try/catch disables 9342 // the optimization of the whole function #14848 9343 try { 9344 var match = COMMENT_DIRECTIVE_REGEXP.exec(node.nodeValue); 9345 if (match) { 9346 var nName = directiveNormalize(match[1]); 9347 if (addDirective(directives, nName, 'M', maxPriority, ignoreDirective)) { 9348 attrs[nName] = trim(match[2]); 9349 } 9350 } 9351 } catch (e) { 9352 // turns out that under some circumstances IE9 throws errors when one attempts to read 9353 // comment's node value. 9354 // Just ignore it and continue. (Can't seem to reproduce in test case.) 9355 } 9356 } 9357 9358 /** 9359 * Given a node with a directive-start it collects all of the siblings until it finds 9360 * directive-end. 9361 * @param node 9362 * @param attrStart 9363 * @param attrEnd 9364 * @returns {*} 9365 */ 9366 function groupScan(node, attrStart, attrEnd) { 9367 var nodes = []; 9368 var depth = 0; 9369 if (attrStart && node.hasAttribute && node.hasAttribute(attrStart)) { 9370 do { 9371 if (!node) { 9372 throw $compileMinErr('uterdir', 9373 'Unterminated attribute, found \'{0}\' but no matching \'{1}\' found.', 9374 attrStart, attrEnd); 9375 } 9376 if (node.nodeType === NODE_TYPE_ELEMENT) { 9377 if (node.hasAttribute(attrStart)) depth++; 9378 if (node.hasAttribute(attrEnd)) depth--; 9379 } 9380 nodes.push(node); 9381 node = node.nextSibling; 9382 } while (depth > 0); 9383 } else { 9384 nodes.push(node); 9385 } 9386 9387 return jqLite(nodes); 9388 } 9389 9390 /** 9391 * Wrapper for linking function which converts normal linking function into a grouped 9392 * linking function. 9393 * @param linkFn 9394 * @param attrStart 9395 * @param attrEnd 9396 * @returns {Function} 9397 */ 9398 function groupElementsLinkFnWrapper(linkFn, attrStart, attrEnd) { 9399 return function groupedElementsLink(scope, element, attrs, controllers, transcludeFn) { 9400 element = groupScan(element[0], attrStart, attrEnd); 9401 return linkFn(scope, element, attrs, controllers, transcludeFn); 9402 }; 9403 } 9404 9405 /** 9406 * A function generator that is used to support both eager and lazy compilation 9407 * linking function. 9408 * @param eager 9409 * @param $compileNodes 9410 * @param transcludeFn 9411 * @param maxPriority 9412 * @param ignoreDirective 9413 * @param previousCompileContext 9414 * @returns {Function} 9415 */ 9416 function compilationGenerator(eager, $compileNodes, transcludeFn, maxPriority, ignoreDirective, previousCompileContext) { 9417 var compiled; 9418 9419 if (eager) { 9420 return compile($compileNodes, transcludeFn, maxPriority, ignoreDirective, previousCompileContext); 9421 } 9422 return /** @this */ function lazyCompilation() { 9423 if (!compiled) { 9424 compiled = compile($compileNodes, transcludeFn, maxPriority, ignoreDirective, previousCompileContext); 9425 9426 // Null out all of these references in order to make them eligible for garbage collection 9427 // since this is a potentially long lived closure 9428 $compileNodes = transcludeFn = previousCompileContext = null; 9429 } 9430 return compiled.apply(this, arguments); 9431 }; 9432 } 9433 9434 /** 9435 * Once the directives have been collected, their compile functions are executed. This method 9436 * is responsible for inlining directive templates as well as terminating the application 9437 * of the directives if the terminal directive has been reached. 9438 * 9439 * @param {Array} directives Array of collected directives to execute their compile function. 9440 * this needs to be pre-sorted by priority order. 9441 * @param {Node} compileNode The raw DOM node to apply the compile functions to 9442 * @param {Object} templateAttrs The shared attribute function 9443 * @param {function(angular.Scope, cloneAttachFn=)} transcludeFn A linking function, where the 9444 * scope argument is auto-generated to the new 9445 * child of the transcluded parent scope. 9446 * @param {JQLite} jqCollection If we are working on the root of the compile tree then this 9447 * argument has the root jqLite array so that we can replace nodes 9448 * on it. 9449 * @param {Object=} originalReplaceDirective An optional directive that will be ignored when 9450 * compiling the transclusion. 9451 * @param {Array.<Function>} preLinkFns 9452 * @param {Array.<Function>} postLinkFns 9453 * @param {Object} previousCompileContext Context used for previous compilation of the current 9454 * node 9455 * @returns {Function} linkFn 9456 */ 9457 function applyDirectivesToNode(directives, compileNode, templateAttrs, transcludeFn, 9458 jqCollection, originalReplaceDirective, preLinkFns, postLinkFns, 9459 previousCompileContext) { 9460 previousCompileContext = previousCompileContext || {}; 9461 9462 var terminalPriority = -Number.MAX_VALUE, 9463 newScopeDirective = previousCompileContext.newScopeDirective, 9464 controllerDirectives = previousCompileContext.controllerDirectives, 9465 newIsolateScopeDirective = previousCompileContext.newIsolateScopeDirective, 9466 templateDirective = previousCompileContext.templateDirective, 9467 nonTlbTranscludeDirective = previousCompileContext.nonTlbTranscludeDirective, 9468 hasTranscludeDirective = false, 9469 hasTemplate = false, 9470 hasElementTranscludeDirective = previousCompileContext.hasElementTranscludeDirective, 9471 $compileNode = templateAttrs.$$element = jqLite(compileNode), 9472 directive, 9473 directiveName, 9474 $template, 9475 replaceDirective = originalReplaceDirective, 9476 childTranscludeFn = transcludeFn, 9477 linkFn, 9478 didScanForMultipleTransclusion = false, 9479 mightHaveMultipleTransclusionError = false, 9480 directiveValue; 9481 9482 // executes all directives on the current element 9483 for (var i = 0, ii = directives.length; i < ii; i++) { 9484 directive = directives[i]; 9485 var attrStart = directive.$$start; 9486 var attrEnd = directive.$$end; 9487 9488 // collect multiblock sections 9489 if (attrStart) { 9490 $compileNode = groupScan(compileNode, attrStart, attrEnd); 9491 } 9492 $template = undefined; 9493 9494 if (terminalPriority > directive.priority) { 9495 break; // prevent further processing of directives 9496 } 9497 9498 directiveValue = directive.scope; 9499 9500 if (directiveValue) { 9501 9502 // skip the check for directives with async templates, we'll check the derived sync 9503 // directive when the template arrives 9504 if (!directive.templateUrl) { 9505 if (isObject(directiveValue)) { 9506 // This directive is trying to add an isolated scope. 9507 // Check that there is no scope of any kind already 9508 assertNoDuplicate('new/isolated scope', newIsolateScopeDirective || newScopeDirective, 9509 directive, $compileNode); 9510 newIsolateScopeDirective = directive; 9511 } else { 9512 // This directive is trying to add a child scope. 9513 // Check that there is no isolated scope already 9514 assertNoDuplicate('new/isolated scope', newIsolateScopeDirective, directive, 9515 $compileNode); 9516 } 9517 } 9518 9519 newScopeDirective = newScopeDirective || directive; 9520 } 9521 9522 directiveName = directive.name; 9523 9524 // If we encounter a condition that can result in transclusion on the directive, 9525 // then scan ahead in the remaining directives for others that may cause a multiple 9526 // transclusion error to be thrown during the compilation process. If a matching directive 9527 // is found, then we know that when we encounter a transcluded directive, we need to eagerly 9528 // compile the `transclude` function rather than doing it lazily in order to throw 9529 // exceptions at the correct time 9530 if (!didScanForMultipleTransclusion && ((directive.replace && (directive.templateUrl || directive.template)) 9531 || (directive.transclude && !directive.$$tlb))) { 9532 var candidateDirective; 9533 9534 for (var scanningIndex = i + 1; (candidateDirective = directives[scanningIndex++]);) { 9535 if ((candidateDirective.transclude && !candidateDirective.$$tlb) 9536 || (candidateDirective.replace && (candidateDirective.templateUrl || candidateDirective.template))) { 9537 mightHaveMultipleTransclusionError = true; 9538 break; 9539 } 9540 } 9541 9542 didScanForMultipleTransclusion = true; 9543 } 9544 9545 if (!directive.templateUrl && directive.controller) { 9546 controllerDirectives = controllerDirectives || createMap(); 9547 assertNoDuplicate('\'' + directiveName + '\' controller', 9548 controllerDirectives[directiveName], directive, $compileNode); 9549 controllerDirectives[directiveName] = directive; 9550 } 9551 9552 directiveValue = directive.transclude; 9553 9554 if (directiveValue) { 9555 hasTranscludeDirective = true; 9556 9557 // Special case ngIf and ngRepeat so that we don't complain about duplicate transclusion. 9558 // This option should only be used by directives that know how to safely handle element transclusion, 9559 // where the transcluded nodes are added or replaced after linking. 9560 if (!directive.$$tlb) { 9561 assertNoDuplicate('transclusion', nonTlbTranscludeDirective, directive, $compileNode); 9562 nonTlbTranscludeDirective = directive; 9563 } 9564 9565 if (directiveValue === 'element') { 9566 hasElementTranscludeDirective = true; 9567 terminalPriority = directive.priority; 9568 $template = $compileNode; 9569 $compileNode = templateAttrs.$$element = 9570 jqLite(compile.$$createComment(directiveName, templateAttrs[directiveName])); 9571 compileNode = $compileNode[0]; 9572 replaceWith(jqCollection, sliceArgs($template), compileNode); 9573
9574 // Support: Chrome < 50 9575 // https://github.com/angular/angular.js/issues/14041 9576 9577 // In the versions of V8 prior to Chrome 50, the document fragment that is created 9578 // in the `replaceWith` function is improperly garbage collected despite still 9579 // being referenced by the `parentNode` property of all of the child nodes. By adding 9580 // a reference to the fragment via a different property, we can avoid that incorrect 9581 // behavior. 9582 // TODO: remove this line after Chrome 50 has been released 9583 $template[0].$$parentNode = $template[0].parentNode; 9584 9585 childTranscludeFn = compilationGenerator(mightHaveMultipleTransclusionError, $template, transcludeFn, terminalPriority, 9586 replaceDirective && replaceDirective.name, { 9587 // Don't pass in: 9588 // - controllerDirectives - otherwise we'll create duplicates controllers 9589 // - newIsolateScopeDirective or templateDirective - comb
vendor: 12,814 bytes, lines 9589-9869
9589ining templates with 9590 // element transclusion doesn't make sense. 9591 // 9592 // We need only nonTlbTranscludeDirective so that we prevent putting transclusion 9593 // on the same element more than once. 9594 nonTlbTranscludeDirective: nonTlbTranscludeDirective 9595 }); 9596 } else { 9597 9598 var slots = createMap(); 9599 9600 if (!isObject(directiveValue)) { 9601 $template = jqLite(jqLiteClone(compileNode)).contents(); 9602 } else { 9603 9604 // We have transclusion slots, 9605 // collect them up, compile them and store their transclusion functions 9606 $template = []; 9607 9608 var slotMap = createMap(); 9609 var filledSlots = createMap(); 9610 9611 // Parse the element selectors 9612 forEach(directiveValue, function(elementSelector, slotName) { 9613 // If an element selector starts with a ? then it is optional 9614 var optional = (elementSelector.charAt(0) === '?'); 9615 elementSelector = optional ? elementSelector.substring(1) : elementSelector; 9616 9617 slotMap[elementSelector] = slotName; 9618 9619 // We explicitly assign `null` since this implies that a slot was defined but not filled. 9620 // Later when calling boundTransclusion functions with a slot name we only error if the 9621 // slot is `undefined` 9622 slots[slotName] = null; 9623 9624 // filledSlots contains `true` for all slots that are either optional or have been 9625 // filled. This is used to check that we have not missed any required slots 9626 filledSlots[slotName] = optional; 9627 }); 9628 9629 // Add the matching elements into their slot 9630 forEach($compileNode.contents(), function(node) { 9631 var slotName = slotMap[directiveNormalize(nodeName_(node))]; 9632 if (slotName) { 9633 filledSlots[slotName] = true; 9634 slots[slotName] = slots[slotName] || []; 9635 slots[slotName].push(node); 9636 } else { 9637 $template.push(node); 9638 } 9639 }); 9640 9641 // Check for required slots that were not filled 9642 forEach(filledSlots, function(filled, slotName) { 9643 if (!filled) { 9644 throw $compileMinErr('reqslot', 'Required transclusion slot `{0}` was not filled.', slotName); 9645 } 9646 }); 9647 9648 for (var slotName in slots) { 9649 if (slots[slotName]) { 9650 // Only define a transclusion function if the slot was filled 9651 slots[slotName] = compilationGenerator(mightHaveMultipleTransclusionError, slots[slotName], transcludeFn); 9652 } 9653 } 9654 } 9655 9656 $compileNode.empty(); // clear contents 9657 childTranscludeFn = compilationGenerator(mightHaveMultipleTransclusionError, $template, transcludeFn, undefined, 9658 undefined, { needsNewScope: directive.$$isolateScope || directive.$$newScope}); 9659 childTranscludeFn.$$slots = slots; 9660 } 9661 } 9662 9663 if (directive.template) { 9664 hasTemplate = true; 9665 assertNoDuplicate('template', templateDirective, directive, $compileNode); 9666 templateDirective = directive; 9667 9668 directiveValue = (isFunction(directive.template)) 9669 ? directive.template($compileNode, templateAttrs) 9670 : directive.template; 9671 9672 directiveValue = denormalizeTemplate(directiveValue); 9673 9674 if (directive.replace) { 9675 replaceDirective = directive; 9676 if (jqLiteIsTextNode(directiveValue)) { 9677 $template = []; 9678 } else { 9679 $template = removeComments(wrapTemplate(directive.templateNamespace, trim(directiveValue))); 9680 } 9681 compileNode = $template[0]; 9682 9683 if ($template.length !== 1 || compileNode.nodeType !== NODE_TYPE_ELEMENT) { 9684 throw $compileMinErr('tplrt', 9685 'Template for directive \'{0}\' must have exactly one root element. {1}', 9686 directiveName, ''); 9687 } 9688 9689 replaceWith(jqCollection, $compileNode, compileNode); 9690 9691 var newTemplateAttrs = {$attr: {}}; 9692 9693 // combine directives from the original node and from the template: 9694 // - take the array of directives for this element 9695 // - split it into two parts, those that already applied (processed) and those that weren't (unprocessed) 9696 // - collect directives from the template and sort them by priority 9697 // - combine directives as: processed + template + unprocessed 9698 var templateDirectives = collectDirectives(compileNode, [], newTemplateAttrs); 9699 var unprocessedDirectives = directives.splice(i + 1, directives.length - (i + 1)); 9700 9701 if (newIsolateScopeDirective || newScopeDirective) { 9702 // The original directive caused the current element to be replaced but this element 9703 // also needs to have a new scope, so we need to tell the template directives 9704 // that they would need to get their scope from further up, if they require transclusion 9705 markDirectiveScope(templateDirectives, newIsolateScopeDirective, newScopeDirective); 9706 } 9707 directives = directives.concat(templateDirectives).concat(unprocessedDirectives); 9708 mergeTemplateAttributes(templateAttrs, newTemplateAttrs); 9709 9710 ii = directives.length; 9711 } else { 9712 $compileNode.html(directiveValue); 9713 } 9714 } 9715 9716 if (directive.templateUrl) { 9717 hasTemplate = true; 9718 assertNoDuplicate('template', templateDirective, directive, $compileNode); 9719 templateDirective = directive; 9720 9721 if (directive.replace) { 9722 replaceDirective = directive; 9723 } 9724 9725 // eslint-disable-next-line no-func-assign 9726 nodeLinkFn = compileTemplateUrl(directives.splice(i, directives.length - i), $compileNode, 9727 templateAttrs, jqCollection, hasTranscludeDirective && childTranscludeFn, preLinkFns, postLinkFns, { 9728 controllerDirectives: controllerDirectives, 9729 newScopeDirective: (newScopeDirective !== directive) && newScopeDirective, 9730 newIsolateScopeDirective: newIsolateScopeDirective, 9731 templateDirective: templateDirective, 9732 nonTlbTranscludeDirective: nonTlbTranscludeDirective 9733 }); 9734 ii = directives.length; 9735 } else if (directive.compile) { 9736 try { 9737 linkFn = directive.compile($compileNode, templateAttrs, childTranscludeFn); 9738 var context = directive.$$originalDirective || directive; 9739 if (isFunction(linkFn)) { 9740 addLinkFns(null, bind(context, linkFn), attrStart, attrEnd); 9741 } else if (linkFn) { 9742 addLinkFns(bind(context, linkFn.pre), bind(context, linkFn.post), attrStart, attrEnd); 9743 } 9744 } catch (e) { 9745 $exceptionHandler(e, startingTag($compileNode)); 9746 } 9747 } 9748 9749 if (directive.terminal) { 9750 nodeLinkFn.terminal = true; 9751 terminalPriority = Math.max(terminalPriority, directive.priority); 9752 } 9753 9754 } 9755 9756 nodeLinkFn.scope = newScopeDirective && newScopeDirective.scope === true; 9757 nodeLinkFn.transcludeOnThisElement = hasTranscludeDirective; 9758 nodeLinkFn.templateOnThisElement = hasTemplate; 9759 nodeLinkFn.transclude = childTranscludeFn; 9760 9761 previousCompileContext.hasElementTranscludeDirective = hasElementTranscludeDirective; 9762 9763 // might be normal or delayed nodeLinkFn depending on if templateUrl is present 9764 return nodeLinkFn; 9765 9766 //////////////////// 9767 9768 function addLinkFns(pre, post, attrStart, attrEnd) { 9769 if (pre) { 9770 if (attrStart) pre = groupElementsLinkFnWrapper(pre, attrStart, attrEnd); 9771 pre.require = directive.require; 9772 pre.directiveName = directiveName; 9773 if (newIsolateScopeDirective === directive || directive.$$isolateScope) { 9774 pre = cloneAndAnnotateFn(pre, {isolateScope: true}); 9775 } 9776 preLinkFns.push(pre); 9777 } 9778 if (post) { 9779 if (attrStart) post = groupElementsLinkFnWrapper(post, attrStart, attrEnd); 9780 post.require = directive.require; 9781 post.directiveName = directiveName; 9782 if (newIsolateScopeDirective === directive || directive.$$isolateScope) { 9783 post = cloneAndAnnotateFn(post, {isolateScope: true}); 9784 } 9785 postLinkFns.push(post); 9786 } 9787 } 9788 9789 function nodeLinkFn(childLinkFn, scope, linkNode, $rootElement, boundTranscludeFn) { 9790 var i, ii, linkFn, isolateScope, controllerScope, elementControllers, transcludeFn, $element, 9791 attrs, scopeBindingInfo; 9792 9793 if (compileNode === linkNode) { 9794 attrs = templateAttrs; 9795 $element = templateAttrs.$$element; 9796 } else { 9797 $element = jqLite(linkNode); 9798 attrs = new Attributes($element, templateAttrs); 9799 } 9800 9801 controllerScope = scope; 9802 if (newIsolateScopeDirective) { 9803 isolateScope = scope.$new(true); 9804 } else if (newScopeDirective) { 9805 controllerScope = scope.$parent; 9806 } 9807 9808 if (boundTranscludeFn) { 9809 // track `boundTranscludeFn` so it can be unwrapped if `transcludeFn` 9810 // is later passed as `parentBoundTranscludeFn` to `publicLinkFn` 9811 transcludeFn = controllersBoundTransclude; 9812 transcludeFn.$$boundTransclude = boundTranscludeFn; 9813 // expose the slots on the `$transclude` function 9814 transcludeFn.isSlotFilled = function(slotName) { 9815 return !!boundTranscludeFn.$$slots[slotName]; 9816 }; 9817 } 9818 9819 if (controllerDirectives) { 9820 elementControllers = setupControllers($element, attrs, transcludeFn, controllerDirectives, isolateScope, scope, newIsolateScopeDirective); 9821 } 9822 9823 if (newIsolateScopeDirective) { 9824 // Initialize isolate scope bindings for new isolate scope directive. 9825 compile.$$addScopeInfo($element, isolateScope, true, !(templateDirective && (templateDirective === newIsolateScopeDirective || 9826 templateDirective === newIsolateScopeDirective.$$originalDirective))); 9827 compile.$$addScopeClass($element, true); 9828 isolateScope.$$isolateBindings = 9829 newIsolateScopeDirective.$$isolateBindings; 9830 scopeBindingInfo = initializeDirectiveBindings(scope, attrs, isolateScope, 9831 isolateScope.$$isolateBindings, 9832 newIsolateScopeDirective); 9833 if (scopeBindingInfo.removeWatches) { 9834 isolateScope.$on('$destroy', scopeBindingInfo.removeWatches); 9835 } 9836 } 9837 9838 // Initialize bindToController bindings 9839 for (var name in elementControllers) { 9840 var controllerDirective = controllerDirectives[name]; 9841 var controller = elementControllers[name]; 9842 var bindings = controllerDirective.$$bindings.bindToController; 9843 9844 if (preAssignBindingsEnabled) { 9845 if (bindings) { 9846 controller.bindingInfo = 9847 initializeDirectiveBindings(controllerScope, attrs, controller.instance, bindings, controllerDirective); 9848 } else { 9849 controller.bindingInfo = {}; 9850 } 9851 9852 var controllerResult = controller(); 9853 if (controllerResult !== controller.instance) { 9854 // If the controller constructor has a return value, overwrite the instance 9855 // from setupControllers 9856 controller.instance = controllerResult; 9857 $element.data('$' + controllerDirective.name + 'Controller', controllerResult); 9858 if (controller.bindingInfo.removeWatches) { 9859 controller.bindingInfo.removeWatches(); 9860 } 9861 controller.bindingInfo = 9862 initializeDirectiveBindings(controllerScope, attrs, controller.instance, bindings, controllerDirective); 9863 } 9864 } else { 9865 controller.instance = controller(); 9866 $element.data('$' + controllerDirective.name + 'Controller', controller.instance); 9867 controller.bindingInfo = 9868 initializeDirectiveBindings(controllerScope, attrs, controller.instance, bindings, controllerDirective); 9869 }
vendor: 5,779 bytes, lines 9870-10010
9870 } 9871 9872 // Bind the required controllers to the controller, if `require` is an object and `bindToController` is truthy 9873 forEach(controllerDirectives, function(controllerDirective, name) { 9874 var require = controllerDirective.require; 9875 if (controllerDirective.bindToController && !isArray(require) && isObject(require)) { 9876 extend(elementControllers[name].instance, getControllers(name, require, $element, elementControllers)); 9877 } 9878 }); 9879 9880 // Handle the init and destroy lifecycle hooks on all controllers that have them 9881 forEach(elementControllers, function(controller) { 9882 var controllerInstance = controller.instance; 9883 if (isFunction(controllerInstance.$onChanges)) { 9884 try { 9885 controllerInstance.$onChanges(controller.bindingInfo.initialChanges); 9886 } catch (e) { 9887 $exceptionHandler(e); 9888 } 9889 } 9890 if (isFunction(controllerInstance.$onInit)) { 9891 try { 9892 controllerInstance.$onInit(); 9893 } catch (e) { 9894 $exceptionHandler(e); 9895 } 9896 } 9897 if (isFunction(controllerInstance.$doCheck)) { 9898 controllerScope.$watch(function() { controllerInstance.$doCheck(); }); 9899 controllerInstance.$doCheck(); 9900 } 9901 if (isFunction(controllerInstance.$onDestroy)) { 9902 controllerScope.$on('$destroy', function callOnDestroyHook() { 9903 controllerInstance.$onDestroy(); 9904 }); 9905 } 9906 }); 9907 9908 // PRELINKING 9909 for (i = 0, ii = preLinkFns.length; i < ii; i++) { 9910 linkFn = preLinkFns[i]; 9911 invokeLinkFn(linkFn, 9912 linkFn.isolateScope ? isolateScope : scope, 9913 $element, 9914 attrs, 9915 linkFn.require && getControllers(linkFn.directiveName, linkFn.require, $element, elementControllers), 9916 transcludeFn 9917 ); 9918 } 9919 9920 // RECURSION 9921 // We only pass the isolate scope, if the isolate directive has a template, 9922 // otherwise the child elements do not belong to the isolate directive. 9923 var scopeToChild = scope; 9924 if (newIsolateScopeDirective && (newIsolateScopeDirective.template || newIsolateScopeDirective.templateUrl === null)) { 9925 scopeToChild = isolateScope; 9926 } 9927 if (childLinkFn) { 9928 childLinkFn(scopeToChild, linkNode.childNodes, undefined, boundTranscludeFn); 9929 } 9930 9931 // POSTLINKING 9932 for (i = postLinkFns.length - 1; i >= 0; i--) { 9933 linkFn = postLinkFns[i]; 9934 invokeLinkFn(linkFn, 9935 linkFn.isolateScope ? isolateScope : scope, 9936 $element, 9937 attrs, 9938 linkFn.require && getControllers(linkFn.directiveName, linkFn.require, $element, elementControllers), 9939 transcludeFn 9940 ); 9941 } 9942 9943 // Trigger $postLink lifecycle hooks 9944 forEach(elementControllers, function(controller) { 9945 var controllerInstance = controller.instance; 9946 if (isFunction(controllerInstance.$postLink)) { 9947 controllerInstance.$postLink(); 9948 } 9949 }); 9950 9951 // This is the function that is injected as `$transclude`. 9952 // Note: all arguments are optional! 9953 function controllersBoundTransclude(scope, cloneAttachFn, futureParentElement, slotName) { 9954 var transcludeControllers; 9955 // No scope passed in: 9956 if (!isScope(scope)) { 9957 slotName = futureParentElement; 9958 futureParentElement = cloneAttachFn; 9959 cloneAttachFn = scope; 9960 scope = undefined; 9961 } 9962 9963 if (hasElementTranscludeDirective) { 9964 transcludeControllers = elementControllers; 9965 } 9966 if (!futureParentElement) { 9967 futureParentElement = hasElementTranscludeDirective ? $element.parent() : $element; 9968 } 9969 if (slotName) { 9970 // slotTranscludeFn can be one of three things: 9971 // * a transclude function - a filled slot 9972 // * `null` - an optional slot that was not filled 9973 // * `undefined` - a slot that was not declared (i.e. invalid) 9974 var slotTranscludeFn = boundTranscludeFn.$$slots[slotName]; 9975 if (slotTranscludeFn) { 9976 return slotTranscludeFn(scope, cloneAttachFn, transcludeControllers, futureParentElement, scopeToChild); 9977 } else if (isUndefined(slotTranscludeFn)) { 9978 throw $compileMinErr('noslot', 9979 'No parent directive that requires a transclusion with slot name "{0}". ' + 9980 'Element: {1}', 9981 slotName, startingTag($element)); 9982 } 9983 } else { 9984 return boundTranscludeFn(scope, cloneAttachFn, transcludeControllers, futureParentElement, scopeToChild); 9985 } 9986 } 9987 } 9988 } 9989 9990 function getControllers(directiveName, require, $element, elementControllers) { 9991 var value; 9992 9993 if (isString(require)) { 9994 var match = require.match(REQUIRE_PREFIX_REGEXP); 9995 var name = require.substring(match[0].length); 9996 var inheritType = match[1] || match[3]; 9997 var optional = match[2] === '?'; 9998 9999 //If only parents then start at the parent element 10000 if (inheritType === '^^') { 10001 $element = $element.parent(); 10002 //Otherwise attempt getting the controller from elementControllers in case 10003 //the element is transcluded (and has no data) and to avoid .data if possible 10004 } else { 10005 value = elementControllers && elementControllers[name]; 10006 value = value && value.instance; 10007 } 10008 10009 if (!value) { 10010 var dataName = '$' + name + 'Controller';
10011 value = inheritType ? $element.inheritedData(dataName) : $element.data(dataName);
vendor: 14,141 bytes, lines 10011-10368
10011 10012 } 10013 10014 if (!value && !optional) { 10015 throw $compileMinErr('ctreq', 10016 'Controller \'{0}\', required by directive \'{1}\', can\'t be found!', 10017 name, directiveName); 10018 } 10019 } else if (isArray(require)) { 10020 value = []; 10021 for (var i = 0, ii = require.length; i < ii; i++) { 10022 value[i] = getControllers(directiveName, require[i], $element, elementControllers); 10023 } 10024 } else if (isObject(require)) { 10025 value = {}; 10026 forEach(require, function(controller, property) { 10027 value[property] = getControllers(directiveName, controller, $element, elementControllers); 10028 }); 10029 } 10030 10031 return value || null; 10032 } 10033 10034 function setupControllers($element, attrs, transcludeFn, controllerDirectives, isolateScope, scope, newIsolateScopeDirective) { 10035 var elementControllers = createMap(); 10036 for (var controllerKey in controllerDirectives) { 10037 var directive = controllerDirectives[controllerKey]; 10038 var locals = { 10039 $scope: directive === newIsolateScopeDirective || directive.$$isolateScope ? isolateScope : scope, 10040 $element: $element, 10041 $attrs: attrs, 10042 $transclude: transcludeFn 10043 }; 10044 10045 var controller = directive.controller; 10046 if (controller === '@') { 10047 controller = attrs[directive.name]; 10048 } 10049 10050 var controllerInstance = $controller(controller, locals, true, directive.controllerAs); 10051 10052 // For directives with element transclusion the element is a comment. 10053 // In this case .data will not attach any data. 10054 // Instead, we save the controllers for the element in a local hash and attach to .data 10055 // later, once we have the actual element. 10056 elementControllers[directive.name] = controllerInstance; 10057 $element.data('$' + directive.name + 'Controller', controllerInstance.instance); 10058 } 10059 return elementControllers; 10060 } 10061 10062 // Depending upon the context in which a directive finds itself it might need to have a new isolated 10063 // or child scope created. For instance: 10064 // * if the directive has been pulled into a template because another directive with a higher priority 10065 // asked for element transclusion 10066 // * if the directive itself asks for transclusion but it is at the root of a template and the original 10067 // element was replaced. See https://github.com/angular/angular.js/issues/12936 10068 function markDirectiveScope(directives, isolateScope, newScope) { 10069 for (var j = 0, jj = directives.length; j < jj; j++) { 10070 directives[j] = inherit(directives[j], {$$isolateScope: isolateScope, $$newScope: newScope}); 10071 } 10072 } 10073 10074 /** 10075 * looks up the directive and decorates it with exception handling and proper parameters. We 10076 * call this the boundDirective. 10077 * 10078 * @param {string} name name of the directive to look up. 10079 * @param {string} location The directive must be found in specific format. 10080 * String containing any of theses characters: 10081 * 10082 * * `E`: element name 10083 * * `A': attribute 10084 * * `C`: class 10085 * * `M`: comment 10086 * @returns {boolean} true if directive was added. 10087 */ 10088 function addDirective(tDirectives, name, location, maxPriority, ignoreDirective, startAttrName, 10089 endAttrName) { 10090 if (name === ignoreDirective) return null; 10091 var match = null; 10092 if (hasDirectives.hasOwnProperty(name)) { 10093 for (var directive, directives = $injector.get(name + Suffix), 10094 i = 0, ii = directives.length; i < ii; i++) { 10095 directive = directives[i]; 10096 if ((isUndefined(maxPriority) || maxPriority > directive.priority) && 10097 directive.restrict.indexOf(location) !== -1) { 10098 if (startAttrName) { 10099 directive = inherit(directive, {$$start: startAttrName, $$end: endAttrName}); 10100 } 10101 if (!directive.$$bindings) { 10102 var bindings = directive.$$bindings = 10103 parseDirectiveBindings(directive, directive.name); 10104 if (isObject(bindings.isolateScope)) { 10105 directive.$$isolateBindings = bindings.isolateScope; 10106 } 10107 } 10108 tDirectives.push(directive); 10109 match = directive; 10110 } 10111 } 10112 } 10113 return match; 10114 } 10115 10116 10117 /** 10118 * looks up the directive and returns true if it is a multi-element directive, 10119 * and therefore requires DOM nodes between -start and -end markers to be grouped 10120 * together. 10121 * 10122 * @param {string} name name of the directive to look up. 10123 * @returns true if directive was registered as multi-element. 10124 */ 10125 function directiveIsMultiElement(name) { 10126 if (hasDirectives.hasOwnProperty(name)) { 10127 for (var directive, directives = $injector.get(name + Suffix), 10128 i = 0, ii = directives.length; i < ii; i++) { 10129 directive = directives[i]; 10130 if (directive.multiElement) { 10131 return true; 10132 } 10133 } 10134 } 10135 return false; 10136 } 10137 10138 /** 10139 * When the element is replaced with HTML template then the new attributes 10140 * on the template need to be merged with the existing attributes in the DOM. 10141 * The desired effect is to have both of the attributes present. 10142 * 10143 * @param {object} dst destination attributes (original DOM) 10144 * @param {object} src source attributes (from the directive template) 10145 */ 10146 function mergeTemplateAttributes(dst, src) { 10147 var srcAttr = src.$attr, 10148 dstAttr = dst.$attr; 10149 10150 // reapply the old attributes to the new element 10151 forEach(dst, function(value, key) { 10152 if (key.charAt(0) !== '$') { 10153 if (src[key] && src[key] !== value) { 10154 if (value.length) { 10155 value += (key === 'style' ? ';' : ' ') + src[key]; 10156 } else { 10157 value = src[key]; 10158 } 10159 } 10160 dst.$set(key, value, true, srcAttr[key]); 10161 } 10162 }); 10163 10164 // copy the new attributes on the old attrs object 10165 forEach(src, function(value, key) { 10166 // Check if we already set this attribute in the loop above. 10167 // `dst` will never contain hasOwnProperty as DOM parser won't let it. 10168 // You will get an "InvalidCharacterError: DOM Exception 5" error if you 10169 // have an attribute like "has-own-property" or "data-has-own-property", etc. 10170 if (!dst.hasOwnProperty(key) && key.charAt(0) !== '$') { 10171 dst[key] = value; 10172 10173 if (key !== 'class' && key !== 'style') { 10174 dstAttr[key] = srcAttr[key]; 10175 } 10176 } 10177 }); 10178 } 10179 10180 10181 function compileTemplateUrl(directives, $compileNode, tAttrs, 10182 $rootElement, childTranscludeFn, preLinkFns, postLinkFns, previousCompileContext) { 10183 var linkQueue = [], 10184 afterTemplateNodeLinkFn, 10185 afterTemplateChildLinkFn, 10186 beforeTemplateCompileNode = $compileNode[0], 10187 origAsyncDirective = directives.shift(), 10188 derivedSyncDirective = inherit(origAsyncDirective, { 10189 templateUrl: null, transclude: null, replace: null, $$originalDirective: origAsyncDirective 10190 }), 10191 templateUrl = (isFunction(origAsyncDirective.templateUrl)) 10192 ? origAsyncDirective.templateUrl($compileNode, tAttrs) 10193 : origAsyncDirective.templateUrl, 10194 templateNamespace = origAsyncDirective.templateNamespace; 10195 10196 $compileNode.empty(); 10197 10198 $templateRequest(templateUrl) 10199 .then(function(content) { 10200 var compileNode, tempTemplateAttrs, $template, childBoundTranscludeFn; 10201 10202 content = denormalizeTemplate(content); 10203 10204 if (origAsyncDirective.replace) { 10205 if (jqLiteIsTextNode(content)) { 10206 $template = []; 10207 } else { 10208 $template = removeComments(wrapTemplate(templateNamespace, trim(content))); 10209 } 10210 compileNode = $template[0]; 10211 10212 if ($template.length !== 1 || compileNode.nodeType !== NODE_TYPE_ELEMENT) { 10213 throw $compileMinErr('tplrt', 10214 'Template for directive \'{0}\' must have exactly one root element. {1}', 10215 origAsyncDirective.name, templateUrl); 10216 } 10217 10218 tempTemplateAttrs = {$attr: {}}; 10219 replaceWith($rootElement, $compileNode, compileNode); 10220 var templateDirectives = collectDirectives(compileNode, [], tempTemplateAttrs); 10221 10222 if (isObject(origAsyncDirective.scope)) { 10223 // the original directive that caused the template to be loaded async required 10224 // an isolate scope 10225 markDirectiveScope(templateDirectives, true); 10226 } 10227 directives = templateDirectives.concat(directives); 10228 mergeTemplateAttributes(tAttrs, tempTemplateAttrs); 10229 } else { 10230 compileNode = beforeTemplateCompileNode; 10231 $compileNode.html(content); 10232 } 10233 10234 directives.unshift(derivedSyncDirective); 10235 10236 afterTemplateNodeLinkFn = applyDirectivesToNode(directives, compileNode, tAttrs, 10237 childTranscludeFn, $compileNode, origAsyncDirective, preLinkFns, postLinkFns, 10238 previousCompileContext); 10239 forEach($rootElement, function(node, i) { 10240 if (node === compileNode) { 10241 $rootElement[i] = $compileNode[0]; 10242 } 10243 }); 10244 afterTemplateChildLinkFn = compileNodes($compileNode[0].childNodes, childTranscludeFn); 10245 10246 while (linkQueue.length) { 10247 var scope = linkQueue.shift(), 10248 beforeTemplateLinkNode = linkQueue.shift(), 10249 linkRootElement = linkQueue.shift(), 10250 boundTranscludeFn = linkQueue.shift(), 10251 linkNode = $compileNode[0]; 10252 10253 if (scope.$$destroyed) continue; 10254 10255 if (beforeTemplateLinkNode !== beforeTemplateCompileNode) { 10256 var oldClasses = beforeTemplateLinkNode.className; 10257 10258 if (!(previousCompileContext.hasElementTranscludeDirective && 10259 origAsyncDirective.replace)) { 10260 // it was cloned therefore we have to clone as well. 10261 linkNode = jqLiteClone(compileNode); 10262 } 10263 replaceWith(linkRootElement, jqLite(beforeTemplateLinkNode), linkNode); 10264 10265 // Copy in CSS classes from original node 10266 safeAddClass(jqLite(linkNode), oldClasses); 10267 } 10268 if (afterTemplateNodeLinkFn.transcludeOnThisElement) { 10269 childBoundTranscludeFn = createBoundTranscludeFn(scope, afterTemplateNodeLinkFn.transclude, boundTranscludeFn); 10270 } else { 10271 childBoundTranscludeFn = boundTranscludeFn; 10272 } 10273 afterTemplateNodeLinkFn(afterTemplateChildLinkFn, scope, linkNode, $rootElement, 10274 childBoundTranscludeFn); 10275 } 10276 linkQueue = null; 10277 }).catch(function(error) { 10278 if (isError(error)) { 10279 $exceptionHandler(error); 10280 } 10281 }); 10282 10283 return function delayedNodeLinkFn(ignoreChildLinkFn, scope, node, rootElement, boundTranscludeFn) { 10284 var childBoundTranscludeFn = boundTranscludeFn; 10285 if (scope.$$destroyed) return; 10286 if (linkQueue) { 10287 linkQueue.push(scope, 10288 node, 10289 rootElement, 10290 childBoundTranscludeFn); 10291 } else { 10292 if (afterTemplateNodeLinkFn.transcludeOnThisElement) { 10293 childBoundTranscludeFn = createBoundTranscludeFn(scope, afterTemplateNodeLinkFn.transclude, boundTranscludeFn); 10294 } 10295 afterTemplateNodeLinkFn(afterTemplateChildLinkFn, scope, node, rootElement, childBoundTranscludeFn); 10296 } 10297 }; 10298 } 10299 10300 10301 /** 10302 * Sorting function for bound directives. 10303 */ 10304 function byPriority(a, b) { 10305 var diff = b.priority - a.priority; 10306 if (diff !== 0) return diff; 10307 if (a.name !== b.name) return (a.name < b.name) ? -1 : 1; 10308 return a.index - b.index; 10309 } 10310 10311 function assertNoDuplicate(what, previousDirective, directive, element) { 10312 10313 function wrapModuleNameIfDefined(moduleName) { 10314 return moduleName ? 10315 (' (module: ' + moduleName + ')') : 10316 ''; 10317 } 10318 10319 if (previousDirective) { 10320 throw $compileMinErr('multidir', 'Multiple directives [{0}{1}, {2}{3}] asking for {4} on: {5}', 10321 previousDirective.name, wrapModuleNameIfDefined(previousDirective.$$moduleName), 10322 directive.name, wrapModuleNameIfDefined(directive.$$moduleName), what, startingTag(element)); 10323 } 10324 } 10325 10326 10327 function addTextInterpolateDirective(directives, text) { 10328 var interpolateFn = $interpolate(text, true); 10329 if (interpolateFn) { 10330 directives.push({ 10331 priority: 0, 10332 compile: function textInterpolateCompileFn(templateNode) { 10333 var templateNodeParent = templateNode.parent(), 10334 hasCompileParent = !!templateNodeParent.length; 10335 10336 // When transcluding a template that has bindings in the root 10337 // we don't have a parent and thus need to add the class during linking fn. 10338 if (hasCompileParent) compile.$$addBindingClass(templateNodeParent); 10339 10340 return function textInterpolateLinkFn(scope, node) { 10341 var parent = node.parent(); 10342 if (!hasCompileParent) compile.$$addBindingClass(parent); 10343 compile.$$addBindingInfo(parent, interpolateFn.expressions); 10344 scope.$watch(interpolateFn, function interpolateFnWatchAction(value) { 10345 node[0].nodeValue = value; 10346 }); 10347 }; 10348 } 10349 }); 10350 } 10351 } 10352 10353 10354 function wrapTemplate(type, template) { 10355 type = lowercase(type || 'html'); 10356 switch (type) { 10357 case 'svg': 10358 case 'math': 10359 var wrapper = window.document.createElement('div'); 10360 wrapper.innerHTML = '<' + type + '>' + template + '</' + type + '>'; 10361 return wrapper.childNodes[0].childNodes; 10362 default: 10363 return template; 10364 } 10365 } 10366 10367 10368 function getTrusted
10368Context(node, attrNormalizedName) { 10369 if (attrNormalizedName === 'srcdoc') { 10370 return $sce.HTML; 10371 } 10372 var tag = nodeName_(node); 10373 // All tags with src attributes require a RESOURCE_URL value, except for 10374 // img and various html5 media tags. 10375 if (attrNormalizedName === 'src' || attrNormalizedName === 'ngSrc') { 10376 if (['img', 'video', 'audio', 'source', 'track'].indexOf(tag) === -1) { 10377 return $sce.RESOURCE_URL; 10378 } 10379 // maction[xlink:href] can source SVG. It's not limited to <maction>. 10380 } else if (attrNormalizedName === 'xlinkHref' || 10381 (tag === 'form' && attrNormalizedName === 'action') || 10382 // links can be stylesheets or imports, which can run script in the current origin 10383 (tag === 'link' && attrNormalizedName === 'href') 10384 ) { 10385 return $sce.RESOURCE_URL; 10386 } 10387 } 10388 10389 10390 function addAttrInterpolateDirective(node, directives, value, name, isNgAttr) { 10391 var trustedContext = getTrustedContext(node, name); 10392 var mustHaveExpression = !isNgAttr; 10393 var allOrNothing = ALL_OR_NOTHING_ATTRS[name] || isNgAttr; 10394 10395 var interpolateFn = $interpolate(value, mustHaveExpression, trustedContext, allOrNothing); 10396 10397 // no interpolation found -> ignore 10398 if (!interpolateFn) return; 10399 10400 if (name === 'multiple' && nodeName_(node) === 'select') { 10401 throw $compileMinErr('selmulti', 10402 'Binding to the \'multiple\' attribute is not supported. Element: {0}', 10403 startingTag(node)); 10404 } 10405 10406 if (EVENT_HANDLER_ATTR_REGEXP.test(name)) { 10407 throw $compileMinErr('nodomevents', 10408 'Interpolations for HTML DOM event attributes are disallowed. Please use the ' + 10409 'ng- versions (such as ng-click instead of onclick) instead.'); 10410 } 10411 10412 directives.push({ 10413 priority: 100, 10414 compile: function() { 10415 return { 10416 pre: function attrInterpolatePreLinkFn(scope, element, attr) { 10417 var $$observers = (attr.$$observers || (attr.$$observers = createMap())
vendor: 23,183 bytes, lines 10417-11047
10417); 10418 10419 // If the attribute has changed since last $interpolate()ed 10420 var newValue = attr[name]; 10421 if (newValue !== value) { 10422 // we need to interpolate again since the attribute value has been updated 10423 // (e.g. by another directive's compile function) 10424 // ensure unset/empty values make interpolateFn falsy 10425 interpolateFn = newValue && $interpolate(newValue, true, trustedContext, allOrNothing); 10426 value = newValue; 10427 } 10428 10429 // if attribute was updated so that there is no interpolation going on we don't want to 10430 // register any observers 10431 if (!interpolateFn) return; 10432 10433 // initialize attr object so that it's ready in case we need the value for isolate 10434 // scope initialization, otherwise the value would not be available from isolate 10435 // directive's linking fn during linking phase 10436 attr[name] = interpolateFn(scope); 10437 10438 ($$observers[name] || ($$observers[name] = [])).$$inter = true; 10439 (attr.$$observers && attr.$$observers[name].$$scope || scope). 10440 $watch(interpolateFn, function interpolateFnWatchAction(newValue, oldValue) { 10441 //special case for class attribute addition + removal 10442 //so that class changes can tap into the animation 10443 //hooks provided by the $animate service. Be sure to 10444 //skip animations when the first digest occurs (when 10445 //both the new and the old values are the same) since 10446 //the CSS classes are the non-interpolated values 10447 if (name === 'class' && newValue !== oldValue) { 10448 attr.$updateClass(newValue, oldValue); 10449 } else { 10450 attr.$set(name, newValue); 10451 } 10452 }); 10453 } 10454 }; 10455 } 10456 }); 10457 } 10458 10459 10460 /** 10461 * This is a special jqLite.replaceWith, which can replace items which 10462 * have no parents, provided that the containing jqLite collection is provided. 10463 * 10464 * @param {JqLite=} $rootElement The root of the compile tree. Used so that we can replace nodes 10465 * in the root of the tree. 10466 * @param {JqLite} elementsToRemove The jqLite element which we are going to replace. We keep 10467 * the shell, but replace its DOM node reference. 10468 * @param {Node} newNode The new DOM node. 10469 */ 10470 function replaceWith($rootElement, elementsToRemove, newNode) { 10471 var firstElementToRemove = elementsToRemove[0], 10472 removeCount = elementsToRemove.length, 10473 parent = firstElementToRemove.parentNode, 10474 i, ii; 10475 10476 if ($rootElement) { 10477 for (i = 0, ii = $rootElement.length; i < ii; i++) { 10478 if ($rootElement[i] === firstElementToRemove) { 10479 $rootElement[i++] = newNode; 10480 for (var j = i, j2 = j + removeCount - 1, 10481 jj = $rootElement.length; 10482 j < jj; j++, j2++) { 10483 if (j2 < jj) { 10484 $rootElement[j] = $rootElement[j2]; 10485 } else { 10486 delete $rootElement[j]; 10487 } 10488 } 10489 $rootElement.length -= removeCount - 1; 10490 10491 // If the replaced element is also the jQuery .context then replace it 10492 // .context is a deprecated jQuery api, so we should set it only when jQuery set it 10493 // http://api.jquery.com/context/ 10494 if ($rootElement.context === firstElementToRemove) { 10495 $rootElement.context = newNode; 10496 } 10497 break; 10498 } 10499 } 10500 } 10501 10502 if (parent) { 10503 parent.replaceChild(newNode, firstElementToRemove); 10504 } 10505 10506 // Append all the `elementsToRemove` to a fragment. This will... 10507 // - remove them from the DOM 10508 // - allow them to still be traversed with .nextSibling 10509 // - allow a single fragment.qSA to fetch all elements being removed 10510 var fragment = window.document.createDocumentFragment(); 10511 for (i = 0; i < removeCount; i++) { 10512 fragment.appendChild(elementsToRemove[i]); 10513 } 10514 10515 if (jqLite.hasData(firstElementToRemove)) { 10516 // Copy over user data (that includes Angular's $scope etc.). Don't copy private 10517 // data here because there's no public interface in jQuery to do that and copying over 10518 // event listeners (which is the main use of private data) wouldn't work anyway. 10519 jqLite.data(newNode, jqLite.data(firstElementToRemove)); 10520 10521 // Remove $destroy event listeners from `firstElementToRemove` 10522 jqLite(firstElementToRemove).off('$destroy'); 10523 } 10524 10525 // Cleanup any data/listeners on the elements and children. 10526 // This includes invoking the $destroy event on any elements with listeners. 10527 jqLite.cleanData(fragment.querySelectorAll('*')); 10528 10529 // Update the jqLite collection to only contain the `newNode` 10530 for (i = 1; i < removeCount; i++) { 10531 delete elementsToRemove[i]; 10532 } 10533 elementsToRemove[0] = newNode; 10534 elementsToRemove.length = 1; 10535 } 10536 10537 10538 function cloneAndAnnotateFn(fn, annotation) { 10539 return extend(function() { return fn.apply(null, arguments); }, fn, annotation); 10540 } 10541 10542 10543 function invokeLinkFn(linkFn, scope, $element, attrs, controllers, transcludeFn) { 10544 try { 10545 linkFn(scope, $element, attrs, controllers, transcludeFn); 10546 } catch (e) { 10547 $exceptionHandler(e, startingTag($element)); 10548 } 10549 } 10550 10551 function strictBindingsCheck(attrName, directiveName) { 10552 if (strictComponentBindingsEnabled) { 10553 throw $compileMinErr('missingattr', 10554 'Attribute \'{0}\' of \'{1}\' is non-optional and must be set!', 10555 attrName, directiveName); 10556 } 10557 } 10558 10559 // Set up $watches for isolate scope and controller bindings. 10560 function initializeDirectiveBindings(scope, attrs, destination, bindings, directive) { 10561 var removeWatchCollection = []; 10562 var initialChanges = {}; 10563 var changes; 10564 10565 forEach(bindings, function initializeBinding(definition, scopeName) { 10566 var attrName = definition.attrName, 10567 optional = definition.optional, 10568 mode = definition.mode, // @, =, <, or & 10569 lastValue, 10570 parentGet, parentSet, compare, removeWatch; 10571 10572 switch (mode) { 10573 10574 case '@': 10575 if (!optional && !hasOwnProperty.call(attrs, attrName)) { 10576 strictBindingsCheck(attrName, directive.name); 10577 destination[scopeName] = attrs[attrName] = undefined; 10578 10579 } 10580 removeWatch = attrs.$observe(attrName, function(value) { 10581 if (isString(value) || isBoolean(value)) { 10582 var oldValue = destination[scopeName]; 10583 recordChanges(scopeName, value, oldValue); 10584 destination[scopeName] = value; 10585 } 10586 }); 10587 attrs.$$observers[attrName].$$scope = scope; 10588 lastValue = attrs[attrName]; 10589 if (isString(lastValue)) { 10590 // If the attribute has been provided then we trigger an interpolation to ensure 10591 // the value is there for use in the link fn 10592 destination[scopeName] = $interpolate(lastValue)(scope); 10593 } else if (isBoolean(lastValue)) { 10594 // If the attributes is one of the BOOLEAN_ATTR then Angular will have converted 10595 // the value to boolean rather than a string, so we special case this situation 10596 destination[scopeName] = lastValue; 10597 } 10598 initialChanges[scopeName] = new SimpleChange(_UNINITIALIZED_VALUE, destination[scopeName]); 10599 removeWatchCollection.push(removeWatch); 10600 break; 10601 10602 case '=': 10603 if (!hasOwnProperty.call(attrs, attrName)) { 10604 if (optional) break; 10605 strictBindingsCheck(attrName, directive.name); 10606 attrs[attrName] = undefined; 10607 } 10608 if (optional && !attrs[attrName]) break; 10609 10610 parentGet = $parse(attrs[attrName]); 10611 if (parentGet.literal) { 10612 compare = equals; 10613 } else { 10614 compare = simpleCompare; 10615 } 10616 parentSet = parentGet.assign || function() { 10617 // reset the change, or we will throw this exception on every $digest 10618 lastValue = destination[scopeName] = parentGet(scope); 10619 throw $compileMinErr('nonassign', 10620 'Expression \'{0}\' in attribute \'{1}\' used with directive \'{2}\' is non-assignable!', 10621 attrs[attrName], attrName, directive.name); 10622 }; 10623 lastValue = destination[scopeName] = parentGet(scope); 10624 var parentValueWatch = function parentValueWatch(parentValue) { 10625 if (!compare(parentValue, destination[scopeName])) { 10626 // we are out of sync and need to copy 10627 if (!compare(parentValue, lastValue)) { 10628 // parent changed and it has precedence 10629 destination[scopeName] = parentValue; 10630 } else { 10631 // if the parent can be assigned then do so 10632 parentSet(scope, parentValue = destination[scopeName]); 10633 } 10634 } 10635 lastValue = parentValue; 10636 return lastValue; 10637 }; 10638 parentValueWatch.$stateful = true; 10639 if (definition.collection) { 10640 removeWatch = scope.$watchCollection(attrs[attrName], parentValueWatch); 10641 } else { 10642 removeWatch = scope.$watch($parse(attrs[attrName], parentValueWatch), null, parentGet.literal); 10643 } 10644 removeWatchCollection.push(removeWatch); 10645 break; 10646 10647 case '<': 10648 if (!hasOwnProperty.call(attrs, attrName)) { 10649 if (optional) break; 10650 strictBindingsCheck(attrName, directive.name); 10651 attrs[attrName] = undefined; 10652 } 10653 if (optional && !attrs[attrName]) break; 10654 10655 parentGet = $parse(attrs[attrName]); 10656 var deepWatch = parentGet.literal; 10657 10658 var initialValue = destination[scopeName] = parentGet(scope); 10659 initialChanges[scopeName] = new SimpleChange(_UNINITIALIZED_VALUE, destination[scopeName]); 10660 10661 removeWatch = scope.$watch(parentGet, function parentValueWatchAction(newValue, oldValue) { 10662 if (oldValue === newValue) { 10663 if (oldValue === initialValue || (deepWatch && equals(oldValue, initialValue))) { 10664 return; 10665 } 10666 oldValue = initialValue; 10667 } 10668 recordChanges(scopeName, newValue, oldValue); 10669 destination[scopeName] = newValue; 10670 }, deepWatch); 10671 10672 removeWatchCollection.push(removeWatch); 10673 break; 10674 10675 case '&': 10676 if (!optional && !hasOwnProperty.call(attrs, attrName)) { 10677 strictBindingsCheck(attrName, directive.name); 10678 } 10679 // Don't assign Object.prototype method to scope 10680 parentGet = attrs.hasOwnProperty(attrName) ? $parse(attrs[attrName]) : noop; 10681 10682 // Don't assign noop to destination if expression is not valid 10683 if (parentGet === noop && optional) break; 10684 10685 destination[scopeName] = function(locals) { 10686 return parentGet(scope, locals); 10687 }; 10688 break; 10689 } 10690 }); 10691 10692 function recordChanges(key, currentValue, previousValue) { 10693 if (isFunction(destination.$onChanges) && !simpleCompare(currentValue, previousValue)) { 10694 // If we have not already scheduled the top level onChangesQueue handler then do so now 10695 if (!onChangesQueue) { 10696 scope.$$postDigest(flushOnChangesQueue); 10697 onChangesQueue = []; 10698 } 10699 // If we have not already queued a trigger of onChanges for this controller then do so now 10700 if (!changes) { 10701 changes = {}; 10702 onChangesQueue.push(triggerOnChangesHook); 10703 } 10704 // If the has been a change on this property already then we need to reuse the previous value 10705 if (changes[key]) { 10706 previousValue = changes[key].previousValue; 10707 } 10708 // Store this change 10709 changes[key] = new SimpleChange(previousValue, currentValue); 10710 } 10711 } 10712 10713 function triggerOnChangesHook() { 10714 destination.$onChanges(changes); 10715 // Now clear the changes so that we schedule onChanges when more changes arrive 10716 changes = undefined; 10717 } 10718 10719 return { 10720 initialChanges: initialChanges, 10721 removeWatches: removeWatchCollection.length && function removeWatches() { 10722 for (var i = 0, ii = removeWatchCollection.length; i < ii; ++i) { 10723 removeWatchCollection[i](); 10724 } 10725 } 10726 }; 10727 } 10728 }]; 10729} 10730 10731function SimpleChange(previous, current) { 10732 this.previousValue = previous; 10733 this.currentValue = current; 10734} 10735SimpleChange.prototype.isFirstChange = function() { return this.previousValue === _UNINITIALIZED_VALUE; }; 10736 10737 10738var PREFIX_REGEXP = /^((?:x|data)[:\-_])/i; 10739var SPECIAL_CHARS_REGEXP = /[:\-_]+(.)/g; 10740 10741/** 10742 * Converts all accepted directives format into proper directive name. 10743 * @param name Name to normalize 10744 */ 10745function directiveNormalize(name) { 10746 return name 10747 .replace(PREFIX_REGEXP, '') 10748 .replace(SPECIAL_CHARS_REGEXP, fnCamelCaseReplace); 10749} 10750 10751/** 10752 * @ngdoc type 10753 * @name $compile.directive.Attributes 10754 * 10755 * @description 10756 * A shared object between directive compile / linking functions which contains normalized DOM 10757 * element attributes. The values reflect current binding state `{{ }}`. The normalization is 10758 * needed since all of these are treated as equivalent in Angular: 10759 * 10760 * ``` 10761 * <span ng:bind="a" ng-bind="a" data-ng-bind="a" x-ng-bind="a"> 10762 * ``` 10763 */ 10764 10765/** 10766 * @ngdoc property 10767 * @name $compile.directive.Attributes#$attr 10768 * 10769 * @description 10770 * A map of DOM element attribute names to the normalized name. This is 10771 * needed to do reverse lookup from normalized name back to actual name. 10772 */ 10773 10774 10775/** 10776 * @ngdoc method 10777 * @name $compile.directive.Attributes#$set 10778 * @kind function 10779 * 10780 * @description 10781 * Set DOM element attribute value. 10782 * 10783 * 10784 * @param {string} name Normalized element attribute name of the property to modify. The name is 10785 * reverse-translated using the {@link ng.$compile.directive.Attributes#$attr $attr} 10786 * property to the original name. 10787 * @param {string} value Value to set the attribute to. The value can be an interpolated string. 10788 */ 10789 10790 10791 10792/** 10793 * Closure compiler type information 10794 */ 10795 10796function nodesetLinkingFn( 10797 /* angular.Scope */ scope, 10798 /* NodeList */ nodeList, 10799 /* Element */ rootElement, 10800 /* function(Function) */ boundTranscludeFn 10801) {} 10802 10803function directiveLinkingFn( 10804 /* nodesetLinkingFn */ nodesetLinkingFn, 10805 /* angular.Scope */ scope, 10806 /* Node */ node, 10807 /* Element */ rootElement, 10808 /* function(Function) */ boundTranscludeFn 10809) {} 10810 10811function tokenDifference(str1, str2) { 10812 var values = '', 10813 tokens1 = str1.split(/\s+/), 10814 tokens2 = str2.split(/\s+/); 10815 10816 outer: 10817 for (var i = 0; i < tokens1.length; i++) { 10818 var token = tokens1[i]; 10819 for (var j = 0; j < tokens2.length; j++) { 10820 if (token === tokens2[j]) continue outer; 10821 } 10822 values += (values.length > 0 ? ' ' : '') + token; 10823 } 10824 return values; 10825} 10826 10827function removeComments(jqNodes) { 10828 jqNodes = jqLite(jqNodes); 10829 var i = jqNodes.length; 10830 10831 if (i <= 1) { 10832 return jqNodes; 10833 } 10834 10835 while (i--) { 10836 var node = jqNodes[i]; 10837 if (node.nodeType === NODE_TYPE_COMMENT || 10838 (node.nodeType === NODE_TYPE_TEXT && node.nodeValue.trim() === '')) { 10839 splice.call(jqNodes, i, 1); 10840 } 10841 } 10842 return jqNodes; 10843} 10844 10845var $controllerMinErr = minErr('$controller'); 10846 10847 10848var CNTRL_REG = /^(\S+)(\s+as\s+([\w$]+))?$/; 10849function identifierForController(controller, ident) { 10850 if (ident && isString(ident)) return ident; 10851 if (isString(controller)) { 10852 var match = CNTRL_REG.exec(controller); 10853 if (match) return match[3]; 10854 } 10855} 10856 10857 10858/** 10859 * @ngdoc provider 10860 * @name $controllerProvider 10861 * @this 10862 * 10863 * @description 10864 * The {@link ng.$controller $controller service} is used by Angular to create new 10865 * controllers. 10866 * 10867 * This provider allows controller registration via the 10868 * {@link ng.$controllerProvider#register register} method. 10869 */ 10870function $ControllerProvider() { 10871 var controllers = {}, 10872 globals = false; 10873 10874 /** 10875 * @ngdoc method 10876 * @name $controllerProvider#has 10877 * @param {string} name Controller name to check. 10878 */ 10879 this.has = function(name) { 10880 return controllers.hasOwnProperty(name); 10881 }; 10882 10883 /** 10884 * @ngdoc method 10885 * @name $controllerProvider#register 10886 * @param {string|Object} name Controller name, or an object map of controllers where the keys are 10887 * the names and the values are the constructors. 10888 * @param {Function|Array} constructor Controller constructor fn (optionally decorated with DI 10889 * annotations in the array notation). 10890 */ 10891 this.register = function(name, constructor) { 10892 assertNotHasOwnProperty(name, 'controller'); 10893 if (isObject(name)) { 10894 extend(controllers, name); 10895 } else { 10896 controllers[name] = constructor; 10897 } 10898 }; 10899 10900 /** 10901 * @ngdoc method 10902 * @name $controllerProvider#allowGlobals 10903 * @description If called, allows `$controller` to find controller constructors on `window` 10904 * 10905 * @deprecated 10906 * sinceVersion="v1.3.0" 10907 * removeVersion="v1.7.0" 10908 * This method of finding controllers has been deprecated. 10909 */ 10910 this.allowGlobals = function() { 10911 globals = true; 10912 }; 10913 10914 10915 this.$get = ['$injector', '$window', function($injector, $window) { 10916 10917 /** 10918 * @ngdoc service 10919 * @name $controller 10920 * @requires $injector 10921 * 10922 * @param {Function|string} constructor If called with a function then it's considered to be the 10923 * controller constructor function. Otherwise it's considered to be a string which is used 10924 * to retrieve the controller constructor using the following steps: 10925 * 10926 * * check if a controller with given name is registered via `$controllerProvider` 10927 * * check if evaluating the string on the current scope returns a constructor 10928 * * if $controllerProvider#allowGlobals, check `window[constructor]` on the global 10929 * `window` object (deprecated, not recommended) 10930 * 10931 * The string can use the `controller as property` syntax, where the controller instance is published 10932 * as the specified property on the `scope`; the `scope` must be injected into `locals` param for this 10933 * to work correctly. 10934 * 10935 * @param {Object} locals Injection locals for Controller. 10936 * @return {Object} Instance of given controller. 10937 * 10938 * @description 10939 * `$controller` service is responsible for instantiating controllers. 10940 * 10941 * It's just a simple call to {@link auto.$injector $injector}, but extracted into 10942 * a service, so that one can override this service with [BC version](https://gist.github.com/1649788). 10943 */ 10944 return function $controller(expression, locals, later, ident) { 10945 // PRIVATE API: 10946 // param `later` --- indicates that the controller's constructor is invoked at a later time. 10947 // If true, $controller will allocate the object with the correct 10948 // prototype chain, but will not invoke the controller until a returned 10949 // callback is invoked. 10950 // param `ident` --- An optional label which overrides the label parsed from the controller 10951 // expression, if any. 10952 var instance, match, constructor, identifier; 10953 later = later === true; 10954 if (ident && isString(ident)) { 10955 identifier = ident; 10956 } 10957 10958 if (isString(expression)) { 10959 match = expression.match(CNTRL_REG); 10960 if (!match) { 10961 throw $controllerMinErr('ctrlfmt', 10962 'Badly formed controller string \'{0}\'. ' + 10963 'Must match `__name__ as __id__` or `__name__`.', expression); 10964 } 10965 constructor = match[1]; 10966 identifier = identifier || match[3]; 10967 expression = controllers.hasOwnProperty(constructor) 10968 ? controllers[constructor] 10969 : getter(locals.$scope, constructor, true) || 10970 (globals ? getter($window, constructor, true) : undefined); 10971 10972 if (!expression) { 10973 throw $controllerMinErr('ctrlreg', 10974 'The controller with the name \'{0}\' is not registered.', constructor); 10975 } 10976 10977 assertArgFn(expression, constructor, true); 10978 } 10979 10980 if (later) { 10981 // Instantiate controller later: 10982 // This machinery is used to create an instance of the object before calling the 10983 // controller's constructor itself. 10984 // 10985 // This allows properties to be added to the controller before the constructor is 10986 // invoked. Primarily, this is used for isolate scope bindings in $compile. 10987 // 10988 // This feature is not intended for use by applications, and is thus not documented 10989 // publicly. 10990 // Object creation: http://jsperf.com/create-constructor/2 10991 var controllerPrototype = (isArray(expression) ? 10992 expression[expression.length - 1] : expression).prototype; 10993 instance = Object.create(controllerPrototype || null); 10994 10995 if (identifier) { 10996 addIdentifier(locals, identifier, instance, constructor || expression.name); 10997 } 10998 10999 return extend(function $controllerInit() { 11000 var result = $injector.invoke(expression, instance, locals, constructor); 11001 if (result !== instance && (isObject(result) || isFunction(result))) { 11002 instance = result; 11003 if (identifier) { 11004 // If result changed, re-assign controllerAs value to scope. 11005 addIdentifier(locals, identifier, instance, constructor || expression.name); 11006 } 11007 } 11008 return instance; 11009 }, { 11010 instance: instance, 11011 identifier: identifier 11012 }); 11013 } 11014 11015 instance = $injector.instantiate(expression, locals, constructor); 11016 11017 if (identifier) { 11018 addIdentifier(locals, identifier, instance, constructor || expression.name); 11019 } 11020 11021 return instance; 11022 }; 11023 11024 function addIdentifier(locals, identifier, instance, name) { 11025 if (!(locals && isObject(locals.$scope))) { 11026 throw minErr('$controller')('noscp', 11027 'Cannot export controller \'{0}\' as \'{1}\'! No $scope object provided via `locals`.', 11028 name, identifier); 11029 } 11030 11031 locals.$scope[identifier] = instance; 11032 } 11033 }]; 11034} 11035 11036/** 11037 * @ngdoc service 11038 * @name $document 11039 * @requires $window 11040 * @this 11041 * 11042 * @description 11043 * A {@link angular.element jQuery or jqLite} wrapper for the browser's `window.document` object. 11044 * 11045 * @example 11046 <example module="documentExample" name="document"> 11047 <file name="index.html">
11048 <div ng-controller="ExampleController"> 11049 <p>$document title: <b ng-bind="title"></b></p> 11050 <p>window.document title: <b ng-bind="windowTitle"></b></p> 11051 </div> 11052 </file> 11053 <file name="script.js"> 11054 angular.module('documentExample', []) 11055 .controller('ExampleController', ['$scope', '$document', function($scope, $document) { 11056 $scope.title = $document[0].title; 11057 $scope.windowTitle = angular.element(window.document)[0].title; 11058 }]); 11059 </file> 11060 </example> 11061 */ 11062function $DocumentProvider() { 11063 this.$get = ['$window', function(window) { 11064 return jqLite(window.document); 11065 }]; 11066} 11067 11068 11069/** 11070 * @private 11071 * @this 11072 * Listens for document visibility change and makes the current status accessible. 11073 */ 11074function $$IsDocumentHiddenProvider() { 11075 this.$get = ['$document', '$rootScope', function($document, $rootScope) { 11076 var doc = $document[0]; 11077 var hidden = doc && doc.hidden; 11078 11079 $document.on('visibilitychange', changeListener); 11080 11081 $rootScope.$on('$destroy', function() { 11082 $document.off('visibilitychange', changeListener); 11083 }); 11084 11085 function changeListener() { 11086 hidden = doc.hidden; 11087 } 11088 11089 return function() { 11090 return hidden; 11091 }; 11092 }]; 11093} 11094 11095/** 11096 * @ngdoc service 11097 * @name $exceptionHandler 11098 * @requires ng.$log 11099 * @this 11100 * 11101 * @description 11102 * Any uncaught exception in angular expressions is delegated to this service. 11103 * The default implementation simply delegates to `$log.error` which logs it into 11104 * the browser console. 11105 * 11106 * In unit tests, if `angular-mocks.js` is loaded, this service is overridden by 11107 * {@link ngMock.$exceptionHandler mock $exceptionHandler} which aids in testing. 11108 * 11109 * ## Example: 11110 * 11111 * The example below will overwrite the default `$exceptionHandler` in order to (a) log uncaught 11112 * errors to the backend for later inspection by the developers and (b) to use `$log.warn()` instead 11113 * of `$log.error()`. 11114 * 11115 * ```js 11116 * angular. 11117 * module('exceptionOverwrite', []). 11118 * factory('$exceptionHandler', ['$log', 'logErrorsToBackend', function($log, logErrorsToBackend) { 11119 * return function myExceptionHandler(exception, cause) { 11120 * logErrorsToBackend(exception, cause); 11121 * $log.warn(exception, cause); 11122 * }; 11123 * }
11123]); 11124 * ``` 11125 * 11126 * <hr /> 11127 * Note, that code executed in event-listeners (even those registered using jqLite's `on`/`bind` 11128 * methods) does not delegate exceptions to the {@link ng.$exceptionHandler $exceptionHandler} 11129 * (unless executed during a digest). 11130 * 11131 * If you wish, you can manually delegate exceptions, e.g. 11132 * `try { ... } catch(e) { $exceptionHandler(e); }` 11133 * 11134 * @param {Error} exception Exception associated with the error. 11135 * @param {string=} cause Optional information about the context in which 11136 * the error was thrown. 11137 * 11138 */ 11139function $ExceptionHandlerProvider() { 11140 this.$get = ['$log', function($log) { 11141 return function(exception, cause) { 11142 $log.error.apply($log, arguments); 11143 }; 11144 }]; 11145} 11146 11147var $$ForceReflowProvider = /** @this */ function() { 11148 this.$get = ['$document', function($document) { 11149 return function(domNode) { 11150 //the line below will force the browser to perform a repaint so 11151 //that all the animated elements within the animation frame will 11152 //be properly updated and drawn on screen. This is required to 11153 //ensure that the preparation animation is properly flushed so that 11154 //the active state picks up from there. DO NOT REMOVE THIS LINE. 11155 //DO NOT OPTIMIZE THIS LINE. THE MINIFIER WILL REMOVE IT OTHERWISE WHICH 11156 //WILL RESULT IN AN UNPREDICTABLE BUG THAT IS VERY HARD TO TRACK DOWN AND 11157 //WILL TAKE YEARS AWAY FROM YOUR LIFE. 11158 if (domNode) { 11159 if (!domNode.nodeType && domNode instanceof jqLite) { 11160 domNode = domNode[0]; 11161 } 11162 } else { 11163 domNode = $document[0].body; 11164 } 11165 return domNode.offsetWidth + 1; 11166 }; 11167 }]; 11168}; 11169 11170var APPLICATION_JSON = 'application/json'; 11171var CONTENT_TYPE_APPLICATION_JSON = {'Content-Type': APPLICATION_JSON + ';charset=utf-8'}; 11172var JSON_START = /^\[|^\{(?!\{)/; 11173var JSON_ENDS = { 11174 '[': /]$/, 11175 '{': /}$/ 11176}; 11177var JSON_PROTECTION_PREFIX = /^\)]\}',?\n/; 11178var $httpMinErr = minErr('$http'); 11179 11180function serializeValue(v) { 11181 if (isObject(v)) { 11182 return isDate(v) ? v.toISOString() : toJson(v); 11183 } 11184 return v; 11185} 11186 11187 11188/** @this */ 11189function $HttpParamSerializerProvider() { 11190 /** 11191 * @ngdoc service 11192 * @name $httpParamSerializer 11193 * @description 11194 * 11195 * Default {@link $http `$http`} params serializer that converts objects to strings 11196 * according to the following rules: 11197 * 11198 * * `{'foo': 'bar'}` results in `foo=bar` 11199 * * `{'foo': Date.now()}` results in `foo=2015-04-01T09%3A50%3A49.262Z` (`toISOString()` and encoded representation of a Date object) 11200 * * `{'foo': ['bar', 'baz']}` results in `foo=bar&foo=baz` (repeated key for each array element) 11201 * * `{'foo': {'bar':'baz'}}` results in `foo=%7B%22bar%22%3A%22baz%22%7D` (stringified and encoded representation of an object) 11202 * 11203 * Note that serializer will sort the request parameters alphabetically. 11204 * */ 11205 11206 this.$get = function() { 11207 return function ngParamSerializer(params) { 11208 if (!params) return ''; 11209 var parts = []; 11210 forEachSorted(params, function(value, key) { 11211 if (value === null || isUndefined(value) || isFunction(value)) return; 11212 if (isArray(value)) { 11213 forEach(value, function(v) { 11214 parts.push(encodeUriQuery(key) + '=' + encodeUriQuery(serializeValue(v))); 11215 }); 11216 } else { 11217 parts.push(encodeUriQuery(key) + '=' + encodeUriQuery(serializeValue(value))); 11218 } 11219 }); 11220 11221 return parts.join('&'); 11222 }; 11223 }; 11224} 11225 11226/** @this */ 11227function $HttpParamSerializerJQLikeProvider() { 11228 /** 11229 * @ngdoc service 11230 * @name $httpParamSerializerJQLike 11231 * 11232 * @description 11233 * 11234 * Alternative {@link $http `$http`} params serializer that follows 11235 * jQuery's [`param()`](http://api.jquery.com/jquery.param/) method logic. 11236 * The serializer will also sort the params alphabetically. 11237 * 11238 * To use it for serializing `$http` request parameters, set it as the `paramSerializer` property: 11239 * 11240 * ```js 11241 * $http({ 11242 * url: myUrl, 11243 * method: 'GET', 11244 * params: myParams, 11245 * paramSerializer: '$httpParamSerializerJQLike' 11246 * }); 11247 * ``` 11248 * 11249 * It is also possible to set it as the default `paramSerializer` in the 11250 * {@link $httpProvider#defaults `$httpProvider`}. 11251 * 11252 * Additionally, you can inject the serializer and use it explicitly, for example to serialize 11253 * form data for submission: 11254 * 11255 * ```js 11256 * .controller(function($http, $httpParamSerializerJQLike) { 11257 * //... 11258 * 11259 * $http({ 11260 * url: myUrl, 11261 * method: 'POST', 11262 * data: $httpParamSerializerJQLike(myData), 11263 * headers: { 11264 * 'Content-Type': 'application/x-www-form-urlencoded' 11265 * } 11266 * }); 11267 * 11268 * }); 11269 * ``` 11270 * 11271 * */ 11272 this.$get = function() { 11273 return function jQueryLikeParamSerializer(params) { 11274 if (!params) return ''; 11275 var parts = []; 11276 serialize(params, '', true); 11277 return parts.join('&'); 11278 11279 function serialize(toSerialize, prefix, topLevel) { 11280 if (toSerialize === null || isUndefined(toSerialize)) return; 11281 if (isArray(toSerialize)) {
vendor: 7,449 bytes, lines 11282-11510
11282 forEach(toSerialize, function(value, index) { 11283 serialize(value, prefix + '[' + (isObject(value) ? index : '') + ']'); 11284 }); 11285 } else if (isObject(toSerialize) && !isDate(toSerialize)) { 11286 forEachSorted(toSerialize, function(value, key) { 11287 serialize(value, prefix + 11288 (topLevel ? '' : '[') + 11289 key + 11290 (topLevel ? '' : ']')); 11291 }); 11292 } else { 11293 parts.push(encodeUriQuery(prefix) + '=' + encodeUriQuery(serializeValue(toSerialize))); 11294 } 11295 } 11296 }; 11297 }; 11298} 11299 11300function defaultHttpResponseTransform(data, headers) { 11301 if (isString(data)) { 11302 // Strip json vulnerability protection prefix and trim whitespace 11303 var tempData = data.replace(JSON_PROTECTION_PREFIX, '').trim(); 11304 11305 if (tempData) { 11306 var contentType = headers('Content-Type'); 11307 var hasJsonContentType = contentType && (contentType.indexOf(APPLICATION_JSON) === 0); 11308 11309 if (hasJsonContentType || isJsonLike(tempData)) { 11310 try { 11311 data = fromJson(tempData); 11312 } catch (e) { 11313 if (!hasJsonContentType) { 11314 return data; 11315 } 11316 throw $httpMinErr('baddata', 'Data must be a valid JSON object. Received: "{0}". ' + 11317 'Parse error: "{1}"', data, e); 11318 } 11319 } 11320 } 11321 } 11322 11323 return data; 11324} 11325 11326function isJsonLike(str) { 11327 var jsonStart = str.match(JSON_START); 11328 return jsonStart && JSON_ENDS[jsonStart[0]].test(str); 11329} 11330 11331/** 11332 * Parse headers into key value object 11333 * 11334 * @param {string} headers Raw headers as a string 11335 * @returns {Object} Parsed headers as key value object 11336 */ 11337function parseHeaders(headers) { 11338 var parsed = createMap(), i; 11339 11340 function fillInParsed(key, val) { 11341 if (key) { 11342 parsed[key] = parsed[key] ? parsed[key] + ', ' + val : val; 11343 } 11344 } 11345 11346 if (isString(headers)) { 11347 forEach(headers.split('\n'), function(line) { 11348 i = line.indexOf(':'); 11349 fillInParsed(lowercase(trim(line.substr(0, i))), trim(line.substr(i + 1))); 11350 }); 11351 } else if (isObject(headers)) { 11352 forEach(headers, function(headerVal, headerKey) { 11353 fillInParsed(lowercase(headerKey), trim(headerVal)); 11354 }); 11355 } 11356 11357 return parsed; 11358} 11359 11360 11361/** 11362 * Returns a function that provides access to parsed headers. 11363 * 11364 * Headers are lazy parsed when first requested. 11365 * @see parseHeaders 11366 * 11367 * @param {(string|Object)} headers Headers to provide access to. 11368 * @returns {function(string=)} Returns a getter function which if called with: 11369 * 11370 * - if called with an argument returns a single header value or null 11371 * - if called with no arguments returns an object containing all headers. 11372 */ 11373function headersGetter(headers) { 11374 var headersObj; 11375 11376 return function(name) { 11377 if (!headersObj) headersObj = parseHeaders(headers); 11378 11379 if (name) { 11380 var value = headersObj[lowercase(name)]; 11381 if (value === undefined) { 11382 value = null; 11383 } 11384 return value; 11385 } 11386 11387 return headersObj; 11388 }; 11389} 11390 11391 11392/** 11393 * Chain all given functions 11394 * 11395 * This function is used for both request and response transforming 11396 * 11397 * @param {*} data Data to transform. 11398 * @param {function(string=)} headers HTTP headers getter fn. 11399 * @param {number} status HTTP status code of the response. 11400 * @param {(Function|Array.<Function>)} fns Function or an array of functions. 11401 * @returns {*} Transformed data. 11402 */ 11403function transformData(data, headers, status, fns) { 11404 if (isFunction(fns)) { 11405 return fns(data, headers, status); 11406 } 11407 11408 forEach(fns, function(fn) { 11409 data = fn(data, headers, status); 11410 }); 11411 11412 return data; 11413} 11414 11415 11416function isSuccess(status) { 11417 return 200 <= status && status < 300; 11418} 11419 11420 11421/** 11422 * @ngdoc provider 11423 * @name $httpProvider 11424 * @this 11425 * 11426 * @description 11427 * Use `$httpProvider` to change the default behavior of the {@link ng.$http $http} service. 11428 * */ 11429function $HttpProvider() { 11430 /** 11431 * @ngdoc property 11432 * @name $httpProvider#defaults 11433 * @description 11434 * 11435 * Object containing default values for all {@link ng.$http $http} requests. 11436 * 11437 * - **`defaults.cache`** - {boolean|Object} - A boolean value or object created with 11438 * {@link ng.$cacheFactory `$cacheFactory`} to enable or disable caching of HTTP responses 11439 * by default. See {@link $http#caching $http Caching} for more information. 11440 * 11441 * - **`defaults.headers`** - {Object} - Default headers for all $http requests. 11442 * Refer to {@link ng.$http#setting-http-headers $http} for documentation on 11443 * setting default headers. 11444 * - **`defaults.headers.common`** 11445 * - **`defaults.headers.post`** 11446 * - **`defaults.headers.put`** 11447 * - **`defaults.headers.patch`** 11448 * 11449 * - **`defaults.jsonpCallbackParam`** - `{string}` - the name of the query parameter that passes the name of the 11450 * callback in a JSONP request. The value of this parameter will be replaced with the expression generated by the 11451 * {@link $jsonpCallbacks} service. Defaults to `'callback'`. 11452 * 11453 * - **`defaults.paramSerializer`** - `{string|function(Object<string,string>):string}` - A function 11454 * used to the prepare string representation of request parameters (specified as an object). 11455 * If specified as string, it is interpreted as a function registered with the {@link auto.$injector $injector}. 11456 * Defaults to {@link ng.$httpParamSerializer $httpParamSerializer}. 11457 * 11458 * - **`defaults.transformRequest`** - 11459 * `{Array<function(data, headersGetter)>|function(data, headersGetter)}` - 11460 * An array of functions (or a single function) which are applied to the request data. 11461 * By default, this is an array with one request transformation function: 11462 * 11463 * - If the `data` property of the request configuration object contains an object, serialize it 11464 * into JSON format. 11465 * 11466 * - **`defaults.transformResponse`** - 11467 * `{Array<function(data, headersGetter, status)>|function(data, headersGetter, status)}` - 11468 * An array of functions (or a single function) which are applied to the response data. By default, 11469 * this is an array which applies one response transformation function that does two things: 11470 * 11471 * - If XSRF prefix is detected, strip it 11472 * (see {@link ng.$http#security-considerations Security Considerations in the $http docs}). 11473 * - If the `Content-Type` is `application/json` or the response looks like JSON, 11474 * deserialize it using a JSON parser. 11475 * 11476 * - **`defaults.xsrfCookieName`** - {string} - Name of cookie containing the XSRF token. 11477 * Defaults value is `'XSRF-TOKEN'`. 11478 * 11479 * - **`defaults.xsrfHeaderName`** - {string} - Name of HTTP header to populate with the 11480 * XSRF token. Defaults value is `'X-XSRF-TOKEN'`. 11481 * 11482 **/ 11483 var defaults = this.defaults = { 11484 // transform incoming response data 11485 transformResponse: [defaultHttpResponseTransform], 11486 11487 // transform outgoing request data 11488 transformRequest: [function(d) { 11489 return isObject(d) && !isFile(d) && !isBlob(d) && !isFormData(d) ? toJson(d) : d; 11490 }], 11491 11492 // default headers 11493 headers: { 11494 common: { 11495 'Accept': 'application/json, text/plain, */*' 11496 }, 11497 post: shallowCopy(CONTENT_TYPE_APPLICATION_JSON), 11498 put: shallowCopy(CONTENT_TYPE_APPLICATION_JSON), 11499 patch: shallowCopy(CONTENT_TYPE_APPLICATION_JSON) 11500 }, 11501 11502 xsrfCookieName: 'XSRF-TOKEN', 11503 xsrfHeaderName: 'X-XSRF-TOKEN', 11504 11505 paramSerializer: '$httpParamSerializer', 11506 11507 jsonpCallbackParam: 'callback' 11508 }; 11509 11510 var useApplyAsync = false;
11511 /** 11512 * @ngdoc method 11513 * @name $httpProvider#useApplyAsync 11514 * @description 11515 * 11516 * Configure $http service to combine processing of multiple http responses received at around 11517 * the same time via {@link ng.$rootScope.Scope#$applyAsync $rootScope.$applyAsync}. This can result in 11518 * significant performance improvement for bigger applications that make many HTTP requests 11519 * concurrently (common during application bootstrap). 11520 * 11521 * Defaults to false. If no value is specified, returns the current configured value. 11522 * 11523 * @param {boolean=} value If true, when requests are loaded, they will schedule a deferred 11524 * "apply" on the next tick, giving time for subsequent requests in a roughly ~10ms window 11525 * to load and share the same digest cycle. 11526 * 11527 * @returns {boolean|Object} If a value is specified, returns the $httpProvider for chaining. 11528 * otherwise, returns the current configured value. 11529 **/ 11530 this.useApplyAsync = function(value) { 11531 if (isDefined(value)) { 11532 useApplyAsync = !!value; 11533 return this; 11534 } 11535 return useApplyAsync; 11536 }; 11537 11538 /** 11539 * @ngdoc property 11540 * @name $httpProvider#interceptors 11541 * @description 11542 * 11543 * Array containing service factories for all synchronous or asynchronous {@link ng.$http $http} 11544 * pre-processing of request or postprocessing of responses. 11545 * 11546 * These service factories are ordered by request, i.e. they are applied in the same order as the 11547 * array, on request, but reverse order, on response. 11548 * 11549 * {@link ng.$http#interceptors Interceptors detailed info} 11550 **/ 11551 var interceptorFactories = this.interceptors = []; 11552 11553 this.$get = ['$browser', '$httpBackend', '$$cookieReader', '$cacheFactory', '$rootScope', '$q', '$injector', '$sce', 11554 function($browser, $httpBackend, $$cookieReader, $cacheFactory, $rootScope, $q, $injector, $sce) { 11555 11556 var defaultCache = $cacheFactory('$http'); 11557 11558 /** 11559 * Make sure that default param serializer is exposed as a function 11560 */ 11561 defaults.paramSerializer = isString(defaults.paramSerializer) ? 11562 $injector.get(defaults.paramSerializer) : defaults.paramSerializer; 11563 11564 /** 11565 * Interceptors stored in reverse order. Inner interceptors before outer interceptors. 11566 * The reversal is needed so that we can build up the interception chain around the 11567 * server request. 11568 */ 11569 var reversedInterceptors = []; 11570 11571 forEach(interceptorFactories, function(interceptorFactory) { 11572 reversedInterceptors.unshift(isString(interceptorFactory) 11573 ? $injector.get(interceptorFactory) : $injector.invoke(interceptorFactory)); 11574 }); 11575 11576 /** 11577 * @ngdoc service 11578 * @kind function 11579 * @name $http 11580 * @requires ng.$httpBackend 11581 * @requires $cacheFactory 11582 * @requires $rootScope 11583 * @requires $q 11584 * @requires $injector 11585 * 11586 * @description 11587 * The `$http` service is a core Angular service that facilitates communication with the remote 11588 * HTTP servers via the browser's [XMLHttpRequest](https://developer.mozilla.org/en/xmlhttprequest) 11589 * object or via [JSONP](http://en.wikipedia.org/wiki/JSONP). 11590 * 11591 * For unit testing applications that use `$http` service, see 11592 * {@link ngMock.$httpBackend $httpBackend mock}. 11593 * 11594 * For a higher level of abstraction, please check out the {@link ngResource.$resource 11595 * $resource} service. 11596 * 11597 * The $http API is based on the {@link ng.$q deferred/promise APIs} exposed by 11598 * the $q service. While for simple usage patterns this doesn't matter much, for advanced usage 11599 * it is important to familiarize yourself with these APIs and the guarantees they provide. 11600 * 11601 * 11602 * ## General usage 11603 * The `$http` service is a function which takes a single argument — a {@link $http#usage configuration object} — 11604 * that is used to generate an HTTP request and returns a {@link ng.$q promise}. 11605 * 11606 * ```js 11607 * // Simple GET request example: 11608 * $http({ 11609 * method: 'GET', 11610 * url: '/someUrl' 11611 * }).then(function successCallback(response) { 11612 * // this callback will be called asynchronously 11613 * // when the response is available 11614 * }, function errorCallback(response) { 11615 * // called asynchronously if an error occurs 11616 * // or server returns response with an error status. 11617 * }); 11618 * ``` 11619 * 11620 * The response object has these properties: 11621 * 11622 * - **data** – `{string|Object}` – The response body transformed with the transform 11623 * functions. 11624 * - **status** – `{number}` – HTTP status code of the response. 11625 * - **headers** – `{function([headerName])}` – Header getter function. 11626 * - **config** – `{Object}` – The configuration object that was used to generate the request. 11627 * - **statusText** – `{string}` – HTTP status text of the response. 11628 * - **xhrStatus** – `{string}` – Status of the XMLHttpRequest (`complete`, `error`, `timeout` or `abort`). 11629 * 11630 * A response status code between 200 and 299 is considered a success status and will result in 11631 * the success callback being called. Any response status code outside of that range is 11632 * considered an error status and will result in the error callback being called. 11633 * Also, status codes less than -1 are normalized to zero. -1 usually means the request was 11634 * aborted, e.g. using a `config.timeout`. 11635 * Note that if the response is a redirect, XMLHttpRequest will transparently follow it, meaning 11636 * that the outcome (success or error) will be determined by the final response status code. 11637 * 11638 * 11639 * ## Shortcut methods 11640 * 11641 * Shortcut methods are also available. All shortcut methods require passing in the URL, and 11642 * request data must be passed in for POST/PUT requests. An optional config can be passed as the 11643 * last argument. 11644 * 11645 * ```js 11646 * $http.get('/someUrl', config).then(successCallback, errorCallback); 11647 * $http.post('/someUrl', data, config).then(successCallback, errorCallback); 11648 * ``` 11649 * 11650 * Complete list of shortcut methods: 11651 * 11652 * - {@link ng.$http#get $http.get} 11653 * - {@link ng.$http#head $http.head} 11654 * - {@link ng.$http#post $http.post} 11655 * - {@link ng.$http#put $http.put} 11656 * - {@link ng.$http#delete $http.delete} 11657 * - {@link ng.$http#jsonp $http.jsonp} 11658 * - {@link ng.$http#patch $http.patch} 11659 * 11660 * 11661 * ## Writing Unit Tests that use $http 11662 * When unit testing (using {@link ngMock ngMock}), it is necessary to call 11663 * {@link ngMock.$httpBackend#flush $httpBackend.flush()} to flush each pending 11664 * request using trained responses. 11665 * 11666 * ``` 11667 * $httpBackend.expectGET(...); 11668 * $http.get(...); 11669 * $httpBackend.flush(); 11670 * ``` 11671 * 11672 * ## Setting HTTP Headers 11673 * 11674 * The $http service will automatically add certain HTTP headers to all requests. These defaults 11675 * can be fully configured by accessing the `$httpProvider.defaults.headers` configuration 11676 * object, which currently contains this default configuration: 11677 * 11678 * - `$httpProvider.defaults.headers.common` (headers that are common for all requests): 11679 * - <code>Accept: application/json, text/plain, \*/\*</code> 11680 * - `$httpProvider.defaults.headers.post`: (header defaults for POST requests) 11681 * - `Content-Type: application/json` 11682 * - `$httpProvider.defaults.headers.put` (header defaults for PUT requests) 11683 * - `Content-Type: application/json` 11684 *
11685 * To add or overwrite these defaults, simply add or remove a property from these configuration 11686 * objects. To add headers for an HTTP method other than POST or PUT, simply add a new object 11687 * with the lowercased HTTP method name as the key, e.g. 11688 * `$httpProvider.defaults.headers.get = { 'My-Header' : 'value' }`. 11689 * 11690 * The defaults can also be set at runtime via the `$http.defaults` object in the same 11691 * fashion. For example: 11692 * 11693 * ``` 11694 * module.run(function($http) { 11695 * $http.defaults.headers.common.Authorization = 'Basic YmVlcDpib29w'; 11696 * }); 11697 * ``` 11698 * 11699 * In addition, you can supply a `headers` property in the config object passed when 11700 * calling `$http(config)`, which overrides the defaults without changing them globally. 11701 * 11702 * To explicitly remove a header automatically added via $httpProvider.defaults.headers on a per request basis, 11703 * Use the `headers` property, setting the desired header to `undefined`. For example: 11704 * 11705 * ```js 11706 * var req = { 11707 * method: 'POST', 11708 * url: 'http://example.com', 11709 * headers: { 11710 * 'Content-Type': undefined 11711 * }, 11712 * data: { test: 'test' } 11713 * } 11714 * 11715 * $http(req).then(function(){...}, function(){...}); 11716 * ``` 11717 * 11718 * ## Transforming Requests and Responses 11719 * 11720 * Both requests and responses can be transformed using transformation functions: `transformRequest` 11721 * and `transformResponse`. These properties can be a single function that returns 11722 * the transformed value (`function(data, headersGetter, status)`) or an array of such transformation functions, 11723 * which allows you to `push` or `unshift` a new transformation function into the transformation chain. 11724 * 11725 * <div class="alert alert-warning"> 11726 * **Note:** Angular does not make a copy of the `data` parameter before it is passed into the `transformRequest` pipeline. 11727 * That means changes to the properties of `data` are not local to the transform function (since Javascript passes objects by reference). 11728 * For example, when calling `$http.get(url, $scope.myObject)`, modifications to the object's properties in a transformRequest 11729 * function will be reflected on the scope and in any templates where the object is data-bound. 11730 * To prevent this, transform functions should have no side-effects. 11731 * If you need to modify properties, it is recommended to make a copy of the data, or create new object to return. 11732 * </div> 11733 * 11734 * ### Default Transformations 11735 * 11736 * The `$httpProvider` provider and `$http` service expose `defaults.transformRequest` and 11737 * `defaults.transformResponse` properties. If a request does not provide its own transformations 11738 * then these will be applied. 11739 * 11740 * You can augment or replace the default transformations by modifying these properties by adding to or 11741 * replacing the array. 11742 * 11743 * Angular
vendor: 7,929 bytes, lines 11743-11916
11743 provides the following default transformations: 11744 * 11745 * Request transformations (`$httpProvider.defaults.transformRequest` and `$http.defaults.transformRequest`) is 11746 * an array with one function that does the following: 11747 * 11748 * - If the `data` property of the request configuration object contains an object, serialize it 11749 * into JSON format. 11750 * 11751 * Response transformations (`$httpProvider.defaults.transformResponse` and `$http.defaults.transformResponse`) is 11752 * an array with one function that does the following: 11753 * 11754 * - If XSRF prefix is detected, strip it (see Security Considerations section below). 11755 * - If the `Content-Type` is `application/json` or the response looks like JSON, 11756 * deserialize it using a JSON parser. 11757 * 11758 * 11759 * ### Overriding the Default Transformations Per Request 11760 * 11761 * If you wish to override the request/response transformations only for a single request then provide 11762 * `transformRequest` and/or `transformResponse` properties on the configuration object passed 11763 * into `$http`. 11764 * 11765 * Note that if you provide these properties on the config object the default transformations will be 11766 * overwritten. If you wish to augment the default transformations then you must include them in your 11767 * local transformation array. 11768 * 11769 * The following code demonstrates adding a new response transformation to be run after the default response 11770 * transformations have been run. 11771 * 11772 * ```js 11773 * function appendTransform(defaults, transform) { 11774 * 11775 * // We can't guarantee that the default transformation is an array 11776 * defaults = angular.isArray(defaults) ? defaults : [defaults]; 11777 * 11778 * // Append the new transformation to the defaults 11779 * return defaults.concat(transform); 11780 * } 11781 * 11782 * $http({ 11783 * url: '...', 11784 * method: 'GET', 11785 * transformResponse: appendTransform($http.defaults.transformResponse, function(value) { 11786 * return doTransform(value); 11787 * }) 11788 * }); 11789 * ``` 11790 * 11791 * 11792 * ## Caching 11793 * 11794 * {@link ng.$http `$http`} responses are not cached by default. To enable caching, you must 11795 * set the config.cache value or the default cache value to TRUE or to a cache object (created 11796 * with {@link ng.$cacheFactory `$cacheFactory`}). If defined, the value of config.cache takes 11797 * precedence over the default cache value. 11798 * 11799 * In order to: 11800 * * cache all responses - set the default cache value to TRUE or to a cache object 11801 * * cache a specific response - set config.cache value to TRUE or to a cache object 11802 * 11803 * If caching is enabled, but neither the default cache nor config.cache are set to a cache object, 11804 * then the default `$cacheFactory("$http")` object is used. 11805 * 11806 * The default cache value can be set by updating the 11807 * {@link ng.$http#defaults `$http.defaults.cache`} property or the 11808 * {@link $httpProvider#defaults `$httpProvider.defaults.cache`} property. 11809 * 11810 * When caching is enabled, {@link ng.$http `$http`} stores the response from the server using 11811 * the relevant cache object. The next time the same request is made, the response is returned 11812 * from the cache without sending a request to the server. 11813 * 11814 * Take note that: 11815 * 11816 * * Only GET and JSONP requests are cached. 11817 * * The cache key is the request URL including search parameters; headers are not considered. 11818 * * Cached responses are returned asynchronously, in the same way as responses from the server. 11819 * * If multiple identical requests are made using the same cache, which is not yet populated, 11820 * one request will be made to the server and remaining requests will return the same response. 11821 * * A cache-control header on the response does not affect if or how responses are cached. 11822 * 11823 * 11824 * ## Interceptors 11825 * 11826 * Before you start creating interceptors, be sure to understand the 11827 * {@link ng.$q $q and deferred/promise APIs}. 11828 * 11829 * For purposes of global error handling, authentication, or any kind of synchronous or 11830 * asynchronous pre-processing of request or postprocessing of responses, it is desirable to be 11831 * able to intercept requests before they are handed to the server and 11832 * responses before they are handed over to the application code that 11833 * initiated these requests. The interceptors leverage the {@link ng.$q 11834 * promise APIs} to fulfill this need for both synchronous and asynchronous pre-processing. 11835 * 11836 * The interceptors are service factories that are registered with the `$httpProvider` by 11837 * adding them to the `$httpProvider.interceptors` array. The factory is called and 11838 * injected with dependencies (if specified) and returns the interceptor. 11839 * 11840 * There are two kinds of interceptors (and two kinds of rejection interceptors): 11841 * 11842 * * `request`: interceptors get called with a http {@link $http#usage config} object. The function is free to 11843 * modify the `config` object or create a new one. The function needs to return the `config` 11844 * object directly, or a promise containing the `config` or a new `config` object. 11845 * * `requestError`: interceptor gets called when a previous interceptor threw an error or 11846 * resolved with a rejection. 11847 * * `response`: interceptors get called with http `response` object. The function is free to 11848 * modify the `response` object or create a new one. The function needs to return the `response` 11849 * object directly, or as a promise containing the `response` or a new `response` object. 11850 * * `responseError`: interceptor gets called when a previous interceptor threw an error or 11851 * resolved with a rejection. 11852 * 11853 * 11854 * ```js 11855 * // register the interceptor as a service 11856 * $provide.factory('myHttpInterceptor', function($q, dependency1, dependency2) { 11857 * return { 11858 * // optional method 11859 * 'request': function(config) { 11860 * // do something on success 11861 * return config; 11862 * }, 11863 * 11864 * // optional method 11865 * 'requestError': function(rejection) { 11866 * // do something on error 11867 * if (canRecover(rejection)) { 11868 * return responseOrNewPromise 11869 * } 11870 * return $q.reject(rejection); 11871 * }, 11872 * 11873 * 11874 * 11875 * // optional method 11876 * 'response': function(response) { 11877 * // do something on success 11878 * return response; 11879 * }, 11880 * 11881 * // optional method 11882 * 'responseError': function(rejection) { 11883 * // do something on error 11884 * if (canRecover(rejection)) { 11885 * return responseOrNewPromise 11886 * } 11887 * return $q.reject(rejection); 11888 * } 11889 * }; 11890 * }); 11891 * 11892 * $httpProvider.interceptors.push('myHttpInterceptor'); 11893 * 11894 * 11895 * // alternatively, register the interceptor via an anonymous factory 11896 * $httpProvider.interceptors.push(function($q, dependency1, dependency2) { 11897 * return { 11898 * 'request': function(config) { 11899 * // same as above 11900 * }, 11901 * 11902 * 'response': function(response) { 11903 * // same as above 11904 * } 11905 * }; 11906 * }); 11907 * ``` 11908 * 11909 * ## Security Considerations 11910 * 11911 * When designing web applications, consider security threats from: 11912 * 11913 * - [JSON vulnerability](http://haacked.com/archive/2008/11/20/anatomy-of-a-subtle-json-vulnerability.aspx) 11914 * - [XSRF](http://en.wikipedia.org/wiki/Cross-site_request_forgery) 11915 * 11916 * Both server and the client must cooperate in order to eliminate these threats. Angular
11916 comes 11917 * pre-configured with strategies that address these issues, but for this to work backend server 11918 * cooperation is required. 11919 * 11920 * ### JSON Vulnerability Protection 11921 * 11922 * A [JSON vulnerability](http://haacked.com/archive/2008/11/20/anatomy-of-a-subtle-json-vulnerability.aspx) 11923 * allows third party website to turn your JSON resource URL into 11924 * [JSONP](http://en.wikipedia.org/wiki/JSONP) request under some conditions. To 11925 * counter this your server can prefix all JSON requests with following string `")]}',\n"`. 11926 * Angular will automatically strip the prefix before processing it as JSON. 11927 * 11928 * For example if your server needs to return: 11929 * ```js 11930 * ['one','two'] 11931 * ``` 11932 * 11933 * which is vulnerable to attack, your server can return: 11934 * ```js 11935 * )]}', 11936 * ['one','two'] 11937 * ``` 11938 * 11939 * Angular will strip the prefix, before processing the JSON. 11940 * 11941 * 11942 * ### Cross Site Request Forgery (XSRF) Protection 11943 * 11944 * [XSRF](http://en.wikipedia.org/wiki/Cross-site_request_forgery) is an attack technique by 11945 * which the attacker can trick an authenticated user into unknowingly executing actions on your 11946 * website. Angular provides a mechanism to counter XSRF. When performing XHR requests, the 11947 * $http service reads a token from a cookie (by default, `XSRF-TOKEN`) and sets it as an HTTP 11948 * header (`X-XSRF-TOKEN`). Since only JavaScript that runs on your domain could read the 11949 * cookie, your server can be assured that the XHR came from JavaScript running on your domain. 11950 * The header will not be set for cross-domain requests. 11951 * 11952 * To take advantage of this, your server needs to set a token in a JavaScript readable session 11953 * cookie called `XSRF-TOKEN` on the first HTTP GET request. On subsequent XHR requests the 11954 * server can verify that the cookie matches `X-XSRF-TOKEN` HTTP header, and therefore be sure 11955 * that only JavaScript running on your domain could have sent the request. The token must be 11956 * unique for each user and must be verifiable by the server (to prevent the JavaScript from 11957 * making up its own tokens). We recommend that the token is a digest of your site's 11958 * authentication cookie with a [salt](https://en.wikipedia.org/wiki/Salt_(cryptography)) 11959 * for added security. 11960 * 11961 * The name of the headers can be specified using the xsrfHeaderName and xsrfCookieName 11962 * properties of either $httpProvider.defaults at config-time, $http.defaults at run-time, 11963 * or the per-request config object. 11964 * 11965 * In order to prevent collisions in environments where multiple Angular apps share the 11966 * same domain or subdomain, we recommend that each application uses unique cookie name. 11967 * 11968 * @param {object} config Object describing the request to be made and how it should be 11969 * processed. The object has following properties: 11970 * 11971 * - **method** – `{string}` – HTTP method (e.g. 'GET', 'POST', etc) 11972 * - **url** – `{string|TrustedObject}` – Absolute or relative URL of the resource that is being requested; 11973 * or an object created by a call to `$sce.trustAsResourceUrl(url)`. 11974 * - **params** – `{Object.<string|Object>}` – Map of strings or objects which will be serialized 11975 * with the `paramSerializer` and appended as GET parameters. 11976 * - **data** – `{string|Object}` – Data to be sent as the request message data. 11977 * - **headers** – `{Object}` – Map of strings or functions which return strings representing 11978 * HTTP headers to send to the server. If the return value of a function is null, the 11979 * header will not be sent. Functions accept a config object as an argument. 11980 * - **eventHandlers** - `{Object}` - Event listeners to be bound to the XMLHttpRequest object. 11981 * To bind events to the XMLHttpRequest upload object, use `uploadEventHandlers`. 11982 * The handler will be called in the context of a `$apply` block. 11983 * - **uploadEventHandlers** - `{Object}` - Event listeners to be bound to the XMLHttpRequest upload 11984 * object. To bind events to the XMLHttpRequest object, use `eventHandlers`. 11985 * The handler will be called in the context of a `$apply` block. 11986 * - **xsrfHeaderName** – `{string}` – Name of HTTP header to populate with the XSRF token. 11987 * - **xsrfCookieName** – `{string}` – Name of cookie containing the XSRF token. 11988 * - **transformRequest** – 11989 * `{function(data, headersGetter)|Array.<function(data, headersGetter)>
11989}` – 11990 * transform function or an array of such functions. The transform function takes the http 11991 * request body and headers and returns its transformed (typically serialized) version. 11992 * See {@link ng.$http#overriding-the-default-transformations-per-request 11993 * Overriding the Default Transformations} 11994 * - **transformResponse** – 11995 * `{function(data, headersGetter, status)|Array.<function(data, headersGetter, status)>}` – 11996 * transform function or an array of such functions. The transform function takes the http 11997 * response body, headers and status and returns its transformed (typically deserialized) version. 11998 * See {@link ng.$http#overriding-the-default-transformations-per-request 11999 * Overriding the Default Transformations} 12000 * - **paramSerializer** - `{string|function(Object<string,string>):string}` - A function used to 12001 * prepare the string representation of request parameters (specified as an object). 12002 * If specified as string, it is interpreted as function registered with the 12003 * {@link $injector $injector}, which means you can create your own serializer 12004 * by registering it as a {@link auto.$provide#service service}. 12005 * The default serializer is the {@link $httpParamSerializer $httpParamSerializer}; 12006 * alternatively, you can use the {@link $httpParamSerializerJQLike $httpParamSerializerJQLike} 12007 * - **cache** – `{boolean|Object}` – A boolean value or object created with 12008 * {@link ng.$cacheFactory `$cacheFactory`} to enable or disable caching of the HTTP response. 12009 * See {@link $http#caching $http Caching} for more information. 12010 * - **timeout** – `{number|Promise}` – timeout in milliseconds, or {@link ng.$q promise} 12011 * that should abort the request when resolved. 12012 * - **withCredentials** - `{boolean}` - whether to set the `withCredentials` flag on the 12013 * XHR object. See [requests with credentials](https://developer.mozilla.org/docs/Web/HTTP/Access_control_CORS#Requests_with_credentials) 12014 * for more information. 12015 * - **responseType** - `{string}` - see 12016 * [XMLHttpRequest.responseType](https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest#xmlhttprequest-responsetype). 12017 * 12018 * @returns {HttpPromise} Returns a {@link ng.$q `Promise}` that will be resolved to a response object 12019 * when the request succeeds or fails. 12020 * 12021 * 12022 * @property {Array.<Object>} pendingRequests Array of config objects for currently pending 12023 * requests. This is primarily meant to be used for debugging purposes. 12024 * 12025 * 12026 * @example 12027<example module="httpExample" name="http-service"> 12028<file name="index.html"> 12029 <div ng-controller="FetchController"> 12030 <select ng-model="method" aria-label="Request method"> 12031 <option>GET</option> 12032 <option>JSONP</option> 12033 </select> 12034 <input type="text" ng-model="url" size="80" aria-label="URL" /> 12035 <button id="fetchbtn" ng-click="fetch()">fetch</button><br> 12036 <button id="samplegetbtn" ng-click="updateModel('GET', 'http-hello.html')">Sample GET</button> 12037 <button id="samplejsonpbtn" 12038 ng-click="updateModel('JSONP', 12039 'https://angularjs.org/greet.php?name=Super%20Hero')"> 12040 Sample JSONP 12041 </button> 12042 <button id="invalidjsonpbtn" 12043 ng-click="updateModel('JSONP', 'https://angularjs.org/doesntexist')"> 12044 Invalid JSONP 12045 </button> 12046 <pre>http status code: {{status}}</pre> 12047 <pre>http response data: {{data}}</pre> 12048 </div> 12049</file> 12050<file name="script.js"> 12051 angular.module('httpExample', []) 12052 .config(['$sceDelegateProvider', function($sceDelegateProvider) { 12053 // We must whitelist the JSONP endpoint that we are using to show that we trust it 12054 $sceDelegateProvider.resourceUrlWhitelist([ 12055 'self', 12056 'https://angularjs.org/**' 12057 ]); 12058 }]) 12059 .controller('FetchController', ['$scope', '$http', '$templateCache', 12060 function($scope, $http, $templateCache) { 12061 $scope.method = 'GET'; 12062 $scope.url = 'http-hello.html'; 12063 12064 $scope.fetch = function() { 12065 $scope.code = null; 12066 $scope.response = null; 12067 12068 $http({method: $scope.method, url: $scope.url, cache: $templateCache}). 12069 then(function(response) { 12070 $scope.status = response.status; 12071 $scope.data = response.data; 12072 }, function(response) { 12073 $scope.data = response.data || 'Request failed'; 12074 $scope.status = response.status; 12075 }); 12076 }; 12077 12078 $scope.updateModel = function(method, url) { 12079 $scope.method = method; 12080 $scope.url = url; 12081 }; 12082 }]); 12083</file> 12084<file name="http-hello.html"> 12085 Hello, $http! 12086</file> 12087<file name="protractor.js" type="protractor"> 12088 var status = element(by.binding('status')); 12089 var data = element(by.binding('data')); 12090 var fetchBtn = element(by.id('fetchbtn')); 12091 var sampleGetBtn = element(by.id('samplegetbtn')); 12092 var invalidJsonpBtn = element(by.id('invalidjsonpbtn')); 12093 12094 it('should make an xhr GET request', function() { 12095 sampleGetBtn.click(); 12096 fetchBtn.click(); 12097 expect(status.getText()).toMatch('200'); 12098 expect(data.getText()).toMatch(/Hello, \$http!/); 12099 }); 12100 12101// Commented out due to flakes. See https://github.com/angular/angular.js/issues/9185 12102// it('should make a JSONP request to angularjs.org', function() { 12103// var sampleJsonpBtn = element(by.id('samplejsonpbtn')); 12104// sampleJsonpBtn.click(); 12105// fetchBtn.click(); 12106// expect(status.getText()).toMatch('200'); 12107// expect(data.getText()).toMatch(/Super Hero!/); 12108// }); 12109
vendor: 4,111 bytes, lines 12110-12228
12110 it('should make JSONP request to invalid URL and invoke the error handler', 12111 function() { 12112 invalidJsonpBtn.click(); 12113 fetchBtn.click(); 12114 expect(status.getText()).toMatch('0'); 12115 expect(data.getText()).toMatch('Request failed'); 12116 }); 12117</file> 12118</example> 12119 */ 12120 function $http(requestConfig) { 12121 12122 if (!isObject(requestConfig)) { 12123 throw minErr('$http')('badreq', 'Http request configuration must be an object. Received: {0}', requestConfig); 12124 } 12125 12126 if (!isString($sce.valueOf(requestConfig.url))) { 12127 throw minErr('$http')('badreq', 'Http request configuration url must be a string or a $sce trusted object. Received: {0}', requestConfig.url); 12128 } 12129 12130 var config = extend({ 12131 method: 'get', 12132 transformRequest: defaults.transformRequest, 12133 transformResponse: defaults.transformResponse, 12134 paramSerializer: defaults.paramSerializer, 12135 jsonpCallbackParam: defaults.jsonpCallbackParam 12136 }, requestConfig); 12137 12138 config.headers = mergeHeaders(requestConfig); 12139 config.method = uppercase(config.method); 12140 config.paramSerializer = isString(config.paramSerializer) ? 12141 $injector.get(config.paramSerializer) : config.paramSerializer; 12142 12143 $browser.$$incOutstandingRequestCount(); 12144 12145 var requestInterceptors = []; 12146 var responseInterceptors = []; 12147 var promise = $q.resolve(config); 12148 12149 // apply interceptors 12150 forEach(reversedInterceptors, function(interceptor) { 12151 if (interceptor.request || interceptor.requestError) { 12152 requestInterceptors.unshift(interceptor.request, interceptor.requestError); 12153 } 12154 if (interceptor.response || interceptor.responseError) { 12155 responseInterceptors.push(interceptor.response, interceptor.responseError); 12156 } 12157 }); 12158 12159 promise = chainInterceptors(promise, requestInterceptors); 12160 promise = promise.then(serverRequest); 12161 promise = chainInterceptors(promise, responseInterceptors); 12162 promise = promise.finally(completeOutstandingRequest); 12163 12164 return promise; 12165 12166 12167 function chainInterceptors(promise, interceptors) { 12168 for (var i = 0, ii = interceptors.length; i < ii;) { 12169 var thenFn = interceptors[i++]; 12170 var rejectFn = interceptors[i++]; 12171 12172 promise = promise.then(thenFn, rejectFn); 12173 } 12174 12175 interceptors.length = 0; 12176 12177 return promise; 12178 } 12179 12180 function completeOutstandingRequest() { 12181 $browser.$$completeOutstandingRequest(noop); 12182 } 12183 12184 function executeHeaderFns(headers, config) { 12185 var headerContent, processedHeaders = {}; 12186 12187 forEach(headers, function(headerFn, header) { 12188 if (isFunction(headerFn)) { 12189 headerContent = headerFn(config); 12190 if (headerContent != null) { 12191 processedHeaders[header] = headerContent; 12192 } 12193 } else { 12194 processedHeaders[header] = headerFn; 12195 } 12196 }); 12197 12198 return processedHeaders; 12199 } 12200 12201 function mergeHeaders(config) { 12202 var defHeaders = defaults.headers, 12203 reqHeaders = extend({}, config.headers), 12204 defHeaderName, lowercaseDefHeaderName, reqHeaderName; 12205 12206 defHeaders = extend({}, defHeaders.common, defHeaders[lowercase(config.method)]); 12207 12208 // using for-in instead of forEach to avoid unnecessary iteration after header has been found 12209 defaultHeadersIteration: 12210 for (defHeaderName in defHeaders) { 12211 lowercaseDefHeaderName = lowercase(defHeaderName); 12212 12213 for (reqHeaderName in reqHeaders) { 12214 if (lowercase(reqHeaderName) === lowercaseDefHeaderName) { 12215 continue defaultHeadersIteration; 12216 } 12217 } 12218 12219 reqHeaders[defHeaderName] = defHeaders[defHeaderName]; 12220 } 12221 12222 // execute if header value is a function for merged headers 12223 return executeHeaderFns(reqHeaders, shallowCopy(config)); 12224 } 12225 12226 function serverRequest(config) { 12227 var headers = config.headers; 12228 var reqData = transformData(config.data, headersGetter(headers), undefined, c
vendor: 20,862 bytes, lines 12228-12845
12228onfig.transformRequest); 12229 12230 // strip content-type if data is undefined 12231 if (isUndefined(reqData)) { 12232 forEach(headers, function(value, header) { 12233 if (lowercase(header) === 'content-type') { 12234 delete headers[header]; 12235 } 12236 }); 12237 } 12238 12239 if (isUndefined(config.withCredentials) && !isUndefined(defaults.withCredentials)) { 12240 config.withCredentials = defaults.withCredentials; 12241 } 12242 12243 // send request 12244 return sendReq(config, reqData).then(transformResponse, transformResponse); 12245 } 12246 12247 function transformResponse(response) { 12248 // make a copy since the response must be cacheable 12249 var resp = extend({}, response); 12250 resp.data = transformData(response.data, response.headers, response.status, 12251 config.transformResponse); 12252 return (isSuccess(response.status)) 12253 ? resp 12254 : $q.reject(resp); 12255 } 12256 } 12257 12258 $http.pendingRequests = []; 12259 12260 /** 12261 * @ngdoc method 12262 * @name $http#get 12263 * 12264 * @description 12265 * Shortcut method to perform `GET` request. 12266 * 12267 * @param {string|TrustedObject} url Absolute or relative URL of the resource that is being requested; 12268 * or an object created by a call to `$sce.trustAsResourceUrl(url)`. 12269 * @param {Object=} config Optional configuration object 12270 * @returns {HttpPromise} Future object 12271 */ 12272 12273 /** 12274 * @ngdoc method 12275 * @name $http#delete 12276 * 12277 * @description 12278 * Shortcut method to perform `DELETE` request. 12279 * 12280 * @param {string|TrustedObject} url Absolute or relative URL of the resource that is being requested; 12281 * or an object created by a call to `$sce.trustAsResourceUrl(url)`. 12282 * @param {Object=} config Optional configuration object 12283 * @returns {HttpPromise} Future object 12284 */ 12285 12286 /** 12287 * @ngdoc method 12288 * @name $http#head 12289 * 12290 * @description 12291 * Shortcut method to perform `HEAD` request. 12292 * 12293 * @param {string|TrustedObject} url Absolute or relative URL of the resource that is being requested; 12294 * or an object created by a call to `$sce.trustAsResourceUrl(url)`. 12295 * @param {Object=} config Optional configuration object 12296 * @returns {HttpPromise} Future object 12297 */ 12298 12299 /** 12300 * @ngdoc method 12301 * @name $http#jsonp 12302 * 12303 * @description 12304 * Shortcut method to perform `JSONP` request. 12305 * 12306 * Note that, since JSONP requests are sensitive because the response is given full access to the browser, 12307 * the url must be declared, via {@link $sce} as a trusted resource URL. 12308 * You can trust a URL by adding it to the whitelist via 12309 * {@link $sceDelegateProvider#resourceUrlWhitelist `$sceDelegateProvider.resourceUrlWhitelist`} or 12310 * by explicitly trusting the URL via {@link $sce#trustAsResourceUrl `$sce.trustAsResourceUrl(url)`}. 12311 * 12312 * JSONP requests must specify a callback to be used in the response from the server. This callback 12313 * is passed as a query parameter in the request. You must specify the name of this parameter by 12314 * setting the `jsonpCallbackParam` property on the request config object. 12315 * 12316 * ``` 12317 * $http.jsonp('some/trusted/url', {jsonpCallbackParam: 'callback'}) 12318 * ``` 12319 * 12320 * You can also specify a default callback parameter name in `$http.defaults.jsonpCallbackParam`. 12321 * Initially this is set to `'callback'`. 12322 * 12323 * <div class="alert alert-danger"> 12324 * You can no longer use the `JSON_CALLBACK` string as a placeholder for specifying where the callback 12325 * parameter value should go. 12326 * </div> 12327 * 12328 * If you would like to customise where and how the callbacks are stored then try overriding 12329 * or decorating the {@link $jsonpCallbacks} service. 12330 * 12331 * @param {string|TrustedObject} url Absolute or relative URL of the resource that is being requested; 12332 * or an object created by a call to `$sce.trustAsResourceUrl(url)`. 12333 * @param {Object=} config Optional configuration object 12334 * @returns {HttpPromise} Future object 12335 */ 12336 createShortMethods('get', 'delete', 'head', 'jsonp'); 12337 12338 /** 12339 * @ngdoc method 12340 * @name $http#post 12341 * 12342 * @description 12343 * Shortcut method to perform `POST` request. 12344 * 12345 * @param {string} url Relative or absolute URL specifying the destination of the request 12346 * @param {*} data Request content 12347 * @param {Object=} config Optional configuration object 12348 * @returns {HttpPromise} Future object 12349 */ 12350 12351 /** 12352 * @ngdoc method 12353 * @name $http#put 12354 * 12355 * @description 12356 * Shortcut method to perform `PUT` request. 12357 * 12358 * @param {string} url Relative or absolute URL specifying the destination of the request 12359 * @param {*} data Request content 12360 * @param {Object=} config Optional configuration object 12361 * @returns {HttpPromise} Future object 12362 */ 12363 12364 /** 12365 * @ngdoc method 12366 * @name $http#patch 12367 * 12368 * @description 12369 * Shortcut method to perform `PATCH` request. 12370 * 12371 * @param {string} url Relative or absolute URL specifying the destination of the request 12372 * @param {*} data Request content 12373 * @param {Object=} config Optional configuration object 12374 * @returns {HttpPromise} Future object 12375 */ 12376 createShortMethodsWithData('post', 'put', 'patch'); 12377 12378 /** 12379 * @ngdoc property 12380 * @name $http#defaults 12381 * 12382 * @description 12383 * Runtime equivalent of the `$httpProvider.defaults` property. Allows configuration of 12384 * default headers, withCredentials as well as request and response transformations. 12385 * 12386 * See "Setting HTTP Headers" and "Transforming Requests and Responses" sections above. 12387 */ 12388 $http.defaults = defaults; 12389 12390 12391 return $http; 12392 12393 12394 function createShortMethods(names) { 12395 forEach(arguments, function(name) { 12396 $http[name] = function(url, config) { 12397 return $http(extend({}, config || {}, { 12398 method: name, 12399 url: url 12400 })); 12401 }; 12402 }); 12403 } 12404 12405 12406 function createShortMethodsWithData(name) { 12407 forEach(arguments, function(name) { 12408 $http[name] = function(url, data, config) { 12409 return $http(extend({}, config || {}, { 12410 method: name, 12411 url: url, 12412 data: data 12413 })); 12414 }; 12415 }); 12416 } 12417 12418 12419 /** 12420 * Makes the request. 12421 * 12422 * !!! ACCESSES CLOSURE VARS: 12423 * $httpBackend, defaults, $log, $rootScope, defaultCache, $http.pendingRequests 12424 */ 12425 function sendReq(config, reqData) { 12426 var deferred = $q.defer(), 12427 promise = deferred.promise, 12428 cache, 12429 cachedResp, 12430 reqHeaders = config.headers, 12431 isJsonp = lowercase(config.method) === 'jsonp', 12432 url = config.url; 12433 12434 if (isJsonp) { 12435 // JSONP is a pretty sensitive operation where we're allowing a script to have full access to 12436 // our DOM and JS space. So we require that the URL satisfies SCE.RESOURCE_URL. 12437 url = $sce.getTrustedResourceUrl(url); 12438 } else if (!isString(url)) { 12439 // If it is not a string then the URL must be a $sce trusted object 12440 url = $sce.valueOf(url); 12441 } 12442 12443 url = buildUrl(url, config.paramSerializer(config.params)); 12444 12445 if (isJsonp) { 12446 // Check the url and add the JSONP callback placeholder 12447 url = sanitizeJsonpCallbackParam(url, config.jsonpCallbackParam); 12448 } 12449 12450 $http.pendingRequests.push(config); 12451 promise.then(removePendingReq, removePendingReq); 12452 12453 if ((config.cache || defaults.cache) && config.cache !== false && 12454 (config.method === 'GET' || config.method === 'JSONP')) { 12455 cache = isObject(config.cache) ? config.cache 12456 : isObject(/** @type {?} */ (defaults).cache) 12457 ? /** @type {?} */ (defaults).cache 12458 : defaultCache; 12459 } 12460 12461 if (cache) { 12462 cachedResp = cache.get(url); 12463 if (isDefined(cachedResp)) { 12464 if (isPromiseLike(cachedResp)) { 12465 // cached request has already been sent, but there is no response yet 12466 cachedResp.then(resolvePromiseWithResult, resolvePromiseWithResult); 12467 } else { 12468 // serving from cache 12469 if (isArray(cachedResp)) { 12470 resolvePromise(cachedResp[1], cachedResp[0], shallowCopy(cachedResp[2]), cachedResp[3], cachedResp[4]); 12471 } else { 12472 resolvePromise(cachedResp, 200, {}, 'OK', 'complete'); 12473 } 12474 } 12475 } else { 12476 // put the promise for the non-transformed response into cache as a placeholder 12477 cache.put(url, promise); 12478 } 12479 } 12480 12481 12482 // if we won't have the response in cache, set the xsrf headers and 12483 // send the request to the backend 12484 if (isUndefined(cachedResp)) { 12485 var xsrfValue = urlIsSameOrigin(config.url) 12486 ? $$cookieReader()[config.xsrfCookieName || defaults.xsrfCookieName] 12487 : undefined; 12488 if (xsrfValue) { 12489 reqHeaders[(config.xsrfHeaderName || defaults.xsrfHeaderName)] = xsrfValue; 12490 } 12491 12492 $httpBackend(config.method, url, reqData, done, reqHeaders, config.timeout, 12493 config.withCredentials, config.responseType, 12494 createApplyHandlers(config.eventHandlers), 12495 createApplyHandlers(config.uploadEventHandlers)); 12496 } 12497 12498 return promise; 12499 12500 function createApplyHandlers(eventHandlers) { 12501 if (eventHandlers) { 12502 var applyHandlers = {}; 12503 forEach(eventHandlers, function(eventHandler, key) { 12504 applyHandlers[key] = function(event) { 12505 if (useApplyAsync) { 12506 $rootScope.$applyAsync(callEventHandler); 12507 } else if ($rootScope.$$phase) { 12508 callEventHandler(); 12509 } else { 12510 $rootScope.$apply(callEventHandler); 12511 } 12512 12513 function callEventHandler() { 12514 eventHandler(event); 12515 } 12516 }; 12517 }); 12518 return applyHandlers; 12519 } 12520 } 12521 12522 12523 /** 12524 * Callback registered to $httpBackend(): 12525 * - caches the response if desired 12526 * - resolves the raw $http promise 12527 * - calls $apply 12528 */ 12529 function done(status, response, headersString, statusText, xhrStatus) { 12530 if (cache) { 12531 if (isSuccess(status)) { 12532 cache.put(url, [status, response, parseHeaders(headersString), statusText, xhrStatus]); 12533 } else { 12534 // remove promise from the cache 12535 cache.remove(url); 12536 } 12537 } 12538 12539 function resolveHttpPromise() { 12540 resolvePromise(response, status, headersString, statusText, xhrStatus); 12541 } 12542 12543 if (useApplyAsync) { 12544 $rootScope.$applyAsync(resolveHttpPromise); 12545 } else { 12546 resolveHttpPromise(); 12547 if (!$rootScope.$$phase) $rootScope.$apply(); 12548 } 12549 } 12550 12551 12552 /** 12553 * Resolves the raw $http promise. 12554 */ 12555 function resolvePromise(response, status, headers, statusText, xhrStatus) { 12556 //status: HTTP response status code, 0, -1 (aborted by timeout / promise) 12557 status = status >= -1 ? status : 0; 12558 12559 (isSuccess(status) ? deferred.resolve : deferred.reject)({ 12560 data: response, 12561 status: status, 12562 headers: headersGetter(headers), 12563 config: config, 12564 statusText: statusText, 12565 xhrStatus: xhrStatus 12566 }); 12567 } 12568 12569 function resolvePromiseWithResult(result) { 12570 resolvePromise(result.data, result.status, shallowCopy(result.headers()), result.statusText, result.xhrStatus); 12571 } 12572 12573 function removePendingReq() { 12574 var idx = $http.pendingRequests.indexOf(config); 12575 if (idx !== -1) $http.pendingRequests.splice(idx, 1); 12576 } 12577 } 12578 12579 12580 function buildUrl(url, serializedParams) { 12581 if (serializedParams.length > 0) { 12582 url += ((url.indexOf('?') === -1) ? '?' : '&') + serializedParams; 12583 } 12584 return url; 12585 } 12586 12587 function sanitizeJsonpCallbackParam(url, key) { 12588 if (/[&?][^=]+=JSON_CALLBACK/.test(url)) { 12589 // Throw if the url already contains a reference to JSON_CALLBACK 12590 throw $httpMinErr('badjsonp', 'Illegal use of JSON_CALLBACK in url, "{0}"', url); 12591 } 12592 12593 var callbackParamRegex = new RegExp('[&?]' + key + '='); 12594 if (callbackParamRegex.test(url)) { 12595 // Throw if the callback param was already provided 12596 throw $httpMinErr('badjsonp', 'Illegal use of callback param, "{0}", in url, "{1}"', key, url); 12597 } 12598 12599 // Add in the JSON_CALLBACK callback param value 12600 url += ((url.indexOf('?') === -1) ? '?' : '&') + key + '=JSON_CALLBACK'; 12601 12602 return url; 12603 } 12604 }]; 12605} 12606 12607/** 12608 * @ngdoc service 12609 * @name $xhrFactory 12610 * @this 12611 * 12612 * @description 12613 * Factory function used to create XMLHttpRequest objects. 12614 * 12615 * Replace or decorate this service to create your own custom XMLHttpRequest objects. 12616 * 12617 * ``` 12618 * angular.module('myApp', []) 12619 * .factory('$xhrFactory', function() { 12620 * return function createXhr(method, url) { 12621 * return new window.XMLHttpRequest({mozSystem: true}); 12622 * }; 12623 * }); 12624 * ``` 12625 * 12626 * @param {string} method HTTP method of the request (GET, POST, PUT, ..) 12627 * @param {string} url URL of the request. 12628 */ 12629function $xhrFactoryProvider() { 12630 this.$get = function() { 12631 return function createXhr() { 12632 return new window.XMLHttpRequest(); 12633 }; 12634 }; 12635} 12636 12637/** 12638 * @ngdoc service 12639 * @name $httpBackend 12640 * @requires $jsonpCallbacks 12641 * @requires $document 12642 * @requires $xhrFactory 12643 * @this 12644 * 12645 * @description 12646 * HTTP backend used by the {@link ng.$http service} that delegates to 12647 * XMLHttpRequest object or JSONP and deals with browser incompatibilities. 12648 * 12649 * You should never need to use this service directly, instead use the higher-level abstractions: 12650 * {@link ng.$http $http} or {@link ngResource.$resource $resource}. 12651 * 12652 * During testing this implementation is swapped with {@link ngMock.$httpBackend mock 12653 * $httpBackend} which can be trained with responses. 12654 */ 12655function $HttpBackendProvider() { 12656 this.$get = ['$browser', '$jsonpCallbacks', '$document', '$xhrFactory', function($browser, $jsonpCallbacks, $document, $xhrFactory) { 12657 return createHttpBackend($browser, $xhrFactory, $browser.defer, $jsonpCallbacks, $document[0]); 12658 }]; 12659} 12660 12661function createHttpBackend($browser, createXhr, $browserDefer, callbacks, rawDocument) { 12662 // TODO(vojta): fix the signature 12663 return function(method, url, post, callback, headers, timeout, withCredentials, responseType, eventHandlers, uploadEventHandlers) { 12664 url = url || $browser.url(); 12665 12666 if (lowercase(method) === 'jsonp') { 12667 var callbackPath = callbacks.createCallback(url); 12668 var jsonpDone = jsonpReq(url, callbackPath, function(status, text) { 12669 // jsonpReq only ever sets status to 200 (OK), 404 (ERROR) or -1 (WAITING) 12670 var response = (status === 200) && callbacks.getResponse(callbackPath); 12671 completeRequest(callback, status, response, '', text, 'complete'); 12672 callbacks.removeCallback(callbackPath); 12673 }); 12674 } else { 12675 12676 var xhr = createXhr(method, url); 12677 12678 xhr.open(method, url, true); 12679 forEach(headers, function(value, key) { 12680 if (isDefined(value)) { 12681 xhr.setRequestHeader(key, value); 12682 } 12683 }); 12684 12685 xhr.onload = function requestLoaded() { 12686 var statusText = xhr.statusText || ''; 12687 12688 // responseText is the old-school way of retrieving response (supported by IE9) 12689 // response/responseType properties were introduced in XHR Level2 spec (supported by IE10) 12690 var response = ('response' in xhr) ? xhr.response : xhr.responseText; 12691 12692 // normalize IE9 bug (http://bugs.jquery.com/ticket/1450) 12693 var status = xhr.status === 1223 ? 204 : xhr.status; 12694 12695 // fix status code when it is 0 (0 status is undocumented). 12696 // Occurs when accessing file resources or on Android 4.1 stock browser 12697 // while retrieving files from application cache. 12698 if (status === 0) { 12699 status = response ? 200 : urlResolve(url).protocol === 'file' ? 404 : 0; 12700 } 12701 12702 completeRequest(callback, 12703 status, 12704 response, 12705 xhr.getAllResponseHeaders(), 12706 statusText, 12707 'complete'); 12708 }; 12709 12710 var requestError = function() { 12711 // The response is always empty 12712 // See https://xhr.spec.whatwg.org/#request-error-steps and https://fetch.spec.whatwg.org/#concept-network-error 12713 completeRequest(callback, -1, null, null, '', 'error'); 12714 }; 12715 12716 var requestAborted = function() { 12717 completeRequest(callback, -1, null, null, '', 'abort'); 12718 }; 12719 12720 var requestTimeout = function() { 12721 // The response is always empty 12722 // See https://xhr.spec.whatwg.org/#request-error-steps and https://fetch.spec.whatwg.org/#concept-network-error 12723 completeRequest(callback, -1, null, null, '', 'timeout'); 12724 }; 12725 12726 xhr.onerror = requestError; 12727 xhr.onabort = requestAborted; 12728 xhr.ontimeout = requestTimeout; 12729 12730 forEach(eventHandlers, function(value, key) { 12731 xhr.addEventListener(key, value); 12732 }); 12733 12734 forEach(uploadEventHandlers, function(value, key) { 12735 xhr.upload.addEventListener(key, value); 12736 }); 12737 12738 if (withCredentials) { 12739 xhr.withCredentials = true; 12740 } 12741 12742 if (responseType) { 12743 try { 12744 xhr.responseType = responseType; 12745 } catch (e) { 12746 // WebKit added support for the json responseType value on 09/03/2013 12747 // https://bugs.webkit.org/show_bug.cgi?id=73648. Versions of Safari prior to 7 are 12748 // known to throw when setting the value "json" as the response type. Other older 12749 // browsers implementing the responseType 12750 // 12751 // The json response type can be ignored if not supported, because JSON payloads are 12752 // parsed on the client-side regardless. 12753 if (responseType !== 'json') { 12754 throw e; 12755 } 12756 } 12757 } 12758 12759 xhr.send(isUndefined(post) ? null : post); 12760 } 12761 12762 if (timeout > 0) { 12763 var timeoutId = $browserDefer(timeoutRequest, timeout); 12764 } else if (isPromiseLike(timeout)) { 12765 timeout.then(timeoutRequest); 12766 } 12767 12768 12769 function timeoutRequest() { 12770 if (jsonpDone) { 12771 jsonpDone(); 12772 } 12773 if (xhr) { 12774 xhr.abort(); 12775 } 12776 } 12777 12778 function completeRequest(callback, status, response, headersString, statusText, xhrStatus) { 12779 // cancel timeout and subsequent timeout promise resolution 12780 if (isDefined(timeoutId)) { 12781 $browserDefer.cancel(timeoutId); 12782 } 12783 jsonpDone = xhr = null; 12784 12785 callback(status, response, headersString, statusText, xhrStatus); 12786 } 12787 }; 12788 12789 function jsonpReq(url, callbackPath, done) { 12790 url = url.replace('JSON_CALLBACK', callbackPath); 12791 // we can't use jQuery/jqLite here because jQuery does crazy stuff with script elements, e.g.: 12792 // - fetches local scripts via XHR and evals them 12793 // - adds and immediately removes script elements from the document 12794 var script = rawDocument.createElement('script'), callback = null; 12795 script.type = 'text/javascript'; 12796 script.src = url; 12797 script.async = true; 12798 12799 callback = function(event) { 12800 script.removeEventListener('load', callback); 12801 script.removeEventListener('error', callback); 12802 rawDocument.body.removeChild(script); 12803 script = null; 12804 var status = -1; 12805 var text = 'unknown'; 12806 12807 if (event) { 12808 if (event.type === 'load' && !callbacks.wasCalled(callbackPath)) { 12809 event = { type: 'error' }; 12810 } 12811 text = event.type; 12812 status = event.type === 'error' ? 404 : 200; 12813 } 12814 12815 if (done) { 12816 done(status, text); 12817 } 12818 }; 12819 12820 script.addEventListener('load', callback); 12821 script.addEventListener('error', callback); 12822 rawDocument.body.appendChild(script); 12823 return callback; 12824 } 12825} 12826 12827var $interpolateMinErr = angular.$interpolateMinErr = minErr('$interpolate'); 12828$interpolateMinErr.throwNoconcat = function(text) { 12829 throw $interpolateMinErr('noconcat', 12830 'Error while interpolating: {0}\nStrict Contextual Escaping disallows ' + 12831 'interpolations that concatenate multiple expressions when a trusted value is ' + 12832 'required. See http://docs.angularjs.org/api/ng.$sce', text); 12833}; 12834 12835$interpolateMinErr.interr = function(text, err) { 12836 return $interpolateMinErr('interr', 'Can\'t interpolate: {0}\n{1}', text, err.toString()); 12837}; 12838 12839/** 12840 * @ngdoc provider 12841 * @name $interpolateProvider 12842 * @this 12843 * 12844 * @description 12845 *
12846 * Used for configuring the interpolation markup. Defaults to `{{` and `}}`. 12847 * 12848 * <div class="alert alert-danger"> 12849 * This feature is sometimes used to mix different markup languages, e.g. to wrap an Angular 12850 * template within a Python Jinja template (or any other template language). Mixing templating 12851 * languages is **very dangerous**. The embedding template language will not safely escape Angular 12852 * expressions, so any user-controlled values in the template will cause Cross Site Scripting (XSS) 12853 * security bugs! 12854 * </div> 12855 * 12856 * @example 12857<example name="custom-interpolation-markup" module="customInterpolationApp"> 12858<file name="index.html"> 12859<script> 12860 var customInterpolationApp = angular.module('customInterpolationApp', []); 12861 12862 customInterpolationApp.config(function($interpolateProvider) { 12863 $interpolateProvider.startSymbol('//'); 12864 $interpolateProvider.endSymbol('//'); 12865 }); 12866 12867 12868 customInterpolationApp.controller('DemoController', function() { 12869 this.label = "This binding is brought you by // interpolation symbols."; 12870 }); 12871</script> 12872<div ng-controller="DemoController as demo"> 12873 //demo.label// 12874</div> 12875</file> 12876<file name="protractor.js" type="protractor"> 12877 it('should interpolate binding with custom symbols', function() { 12878 expect(element(by.binding('demo.label')).getText()).toBe('This binding is brought you by // interpolation symbols.'); 12879 }); 12880</file> 12881</example> 12882 */ 12883function $InterpolateProvider() { 12884 var startSymbol = '{{'; 12885 var endSymbol = '}}'; 12886 12887 /** 12888 * @ngdoc method 12889 * @name $interpolateProvider#startSymbol 12890 * @description 12891 * Symbol to denote start of expression in the interpolated string. Defaults to `{{`. 12892 * 12893 * @param {string=} value new value to set the starting symbol to. 12894 * @returns {string|self} Returns the symbol when used as getter and self if used as setter. 12895 */ 12896 this.startSymbol = function(value) { 12897 if (value) { 12898 startSymbol = value; 12899 return this; 12900 } else { 12901 return startSymbol; 12902 } 12903 }; 12904 12905 /** 12906 * @ngdoc method 12907 * @name $interpolateProvider#endSymbol 12908 * @description 12909 * Symbol to denote the end of expression in the interpolated string. Defaults to `}}`. 12910 * 12911 * @param {string=} value new value to set the ending symbol to. 12912 * @returns {string|self} Returns the symbol when used as getter and self if used as setter. 12913 */ 12914 this.endSymbol = function(value) { 12915 if (value) { 12916 endSymbol = value; 12917 return this; 12918 } else { 12919 return endSymbol; 12920 } 12921 }; 12922 12923 12924 this.$get = ['$parse', '$exceptionHandler', '$sce', function($parse, $exceptionHandler, $sce) { 12925 var startSymbolLength = startSymbol.length, 12926 endSymbolLength = endSymbol.length, 12927 escapedStartRegexp = new RegExp(startSymbol.replace(/./g, escape), 'g'), 12928 escapedEndRegexp = new RegExp(endSymbol.replace(/./g, escape), 'g'); 12929 12930 function escape(ch) { 12931 return '\\\\\\' + ch; 12932 } 12933 12934 function unescapeText(text) { 12935 return text.replace(escapedStartRegexp, startSymbol). 12936 replace(escapedEndRegexp, endSymbol); 12937 } 12938 12939 // TODO: this is the same as the constantWatchDelegate in parse.js 12940 function constantWatchDelegate(scope, listener, objectEquality, constantInterp) { 12941 var unwatch = scope.$watch(function constantInterpolateWatch(scope) { 12942 unwatch(); 12943 return constantInterp(scope); 12944 }, listener, objectEquality); 12945 return unwatch; 12946 } 12947 12948 /** 12949 * @ngdoc service 12950 * @name $interpolate 12951 * @kind function 12952 * 12953 * @requires $parse 12954 * @requires $sce 12955 * 12956 * @description 12957 * 12958 * Compiles a string with markup into an interpolation function. This service is used by the 12959 * HTML {@link ng.$compile $compile} service for data binding. See 12960 * {@link ng.$interpolateProvider $interpolateProvider} for configuring the 12961 * interpolation markup. 12962 * 12963 * 12964 * ```js 12965 * var $interpolate = ...; // injected 12966 * var exp = $interpolate('Hello {{name | uppercase}}!'); 12967 * expect(exp({name:'Angular'})).toEqual('Hello ANGULAR!'); 12968 * ``` 12969 * 12970 * `$interpolate` takes an optional fourth argument, `allOrNothing`. If `allOrNothing` is 12971 * `true`, the interpolation function will return `undefined` unless all embedded expressions 12972 * evaluate to a value other than `undefined`. 12973 * 12974 * ```js 12975 * var $interpolate = ...; // injected 12976 * var context = {greeting: 'Hello', name: undefined }; 12977 * 12978 * // default "forgiving" mode 12979 * var exp = $interpolate('{{greeting}} {{name}}!'); 12980 * expect(exp(context)).toEqual('Hello !'); 12981 * 12982 * // "allOrNothing" mode 12983 * exp = $interpolate('{{greeting}} {{name}}!', false, null, true); 12984 * expect(exp(context)).toBeUndefined(); 12985 * context.name = 'Angular'; 12986 * expect(exp(context)).toEqual('Hello Angular!'); 12987 * ``` 12988 * 12989 * `allOrNothing` is useful for interpolating URLs. `ngSrc` and `ngSrcset` use this behavior. 12990 * 12991 * #### Escaped Interpolation 12992 * $interpolate provides a mechanism for escaping interpolation markers. Start and end markers 12993 * can be escaped by preceding each of their characters with a REVERSE SOLIDUS U+005C (backslash). 12994 * It will be rendered as a regular start/end marker, and will not be interpreted as an expression 12995 * or binding. 12996 * 12997 * This enables web-servers to prevent script injection attacks and defacing attacks, to some 12998 * degree, while also enabling code examples to work without relying on the 12999 * {@link ng.directive:ngNonBindable ngNonBindable} directive. 13000 * 13001 * **For security purposes, it is strongly encouraged that web servers escape user-supplied data, 13002 * replacing angle brackets (<, >) with &lt; and &gt; respectively, and replacing all 13003 * interpolation start/end markers with their escaped counterparts.** 13004 * 13005 * Escaped interpolation markers are only replaced with the actual interpolation markers in rendered 13006 * output when the $interpolate service processes the text. So, for HTML elements interpolated 13007 * by {@link ng.$compile $compile}
13007, or otherwise interpolated with the `mustHaveExpression` parameter 13008 * set to `true`, the interpolated text must contain an unescaped interpolation expression. As such, 13009 * this is typically useful only when user-data is used in rendering a template from the server, or 13010 * when otherwise untrusted data is used by a directive. 13011 * 13012 * <example name="interpolation"> 13013 * <file name="index.html"> 13014 * <div ng-init="username='A user'"> 13015 * <p ng-init="apptitle='Escaping demo'">{{apptitle}}: \{\{ username = "defaced value"; \}\} 13016 * </p> 13017 * <p><strong>{{username}}</strong> attempts to inject code which will deface the 13018 * application, but fails to accomplish their task, because the server has correctly 13019 * escaped the interpolation start/end markers with REVERSE SOLIDUS U+005C (backslash) 13020 * characters.</p> 13021 * <p>Instead, the result of the attempted script injection is visible, and can be removed 13022 * from the database by an administrator.</p> 13023 * </div> 13024 * </file> 13025 * </example> 13026 * 13027 * @knownIssue 13028 * It is currently not possible for an interpolated expression to contain the interpolation end 13029 * symbol. For example, `{{ '}}' }}` will be incorrectly interpreted as `{{ ' }}` + `' }}`, i.e. 13030 * an interpolated expression consisting of a single-quote (`'`) and the `' }}` string. 13031 * 13032 * @knownIssue 13033 * All directives and components must use the standard `{{` `}}` interpolation symbols 13034 * in their templates. If you change the application interpolation symbols the {@link $compile} 13035 * service will attempt to denormalize the standard symbols to the custom symbols. 13036 * The denormalization process is not clever enough to know not to replace instances of the standard 13037 * symbols where they would not normally be treated as interpolation symbols. For example in the following 13038 * code snippet the closing braces of the literal object will get incorrectly denormalized: 13039 * 13040 * ``` 13041 * <div data-context='{"context":{"id":3,"type":"page"}}"> 13042 * ``` 13043 * 13044 * The workaround is to ensure that such instances are separated by whitespace: 13045 * ``` 13046 * <div data-context='{"context":{"id":3,"type":"page"} }"> 13047 * ``` 13048 * 13049 * See https://github.com/angular/angular.js/pull/14610#issuecomment-219401099 for more information. 13050 * 13051 * @param {string} text The text with markup to interpolate. 13052 * @param {boolean=} mustHaveExpression if set to true then the interpolation string must have 13053 * embedded expression in order to return an interpolation function. Strings with no 13054 * embedded expression will return null for the interpolation function. 13055 * @param {string=} trustedContext when provided, the returned function passes the interpolated 13056 * result through {@link ng.$sce#getTrusted $sce.getTrusted(interpolatedResult, 13057 * trustedContext)} before returning it. Refer to the {@link ng.$sce $sce} service that 13058 * provides Strict Contextual Escaping for details. 13059 * @param {boolean=} allOrNothing if `true`, then the returned function returns undefined 13060 * unless all embedded expressions evaluate to a value other than `undefined`. 13061 * @returns {function(context)} an interpolation function which is used to compute the 13062 * interpolated string. The function has these parameters: 13063 * 13064 * - `context`: evaluation context for all expressions embedded in the interpolated text 13065 */ 13066 function $interpolate(text, mustHaveExpression, trustedContext, allOrNothing) { 13067 // Provide a quick exit and simplified result function for text with no interpolation 13068 if (!text.length || text.indexOf(startSymbol) === -1) { 13069 var constantInterp; 13070 if (!mustHaveExpression) { 13071 var unescapedText = unescapeText(text); 13072 constantInterp = valueFn(unescapedText); 13073 constantInterp.exp = text; 13074 constantInterp.expressions = []; 13075 constantInterp.$$watchDelegate = constantWatchDelegate; 13076 } 13077 return constantInterp; 13078 } 13079 13080 allOrNothing = !!allOrNothing; 13081 var startIndex, 13082 endIndex, 13083 index = 0, 13084 expressions = [], 13085 parseFns = [], 13086 textLength = text.length, 13087 exp, 13088 concat = [], 13089 expressionPositions = []; 13090 13091 while (index < textLength) { 13092 if (((startIndex = text.indexOf(startSymbol, index)) !== -1) && 13093 ((endIndex = text.indexOf(endSymbol, startIndex + startSymbolLength)) !== -1)) { 13094 if (index !== startIndex) { 13095 concat.push(unescapeText(text.substring(index, startIndex))); 13096 } 13097 exp = text.substring(startIndex + startSymbolLength, endIndex); 13098 expressions.push(exp); 13099 parseFns.push($parse(exp, parseStringifyInterceptor));
vendor: 4,127 bytes, lines 13100-13225
13100 index = endIndex + endSymbolLength; 13101 expressionPositions.push(concat.length); 13102 concat.push(''); 13103 } else { 13104 // we did not find an interpolation, so we have to add the remainder to the separators array 13105 if (index !== textLength) { 13106 concat.push(unescapeText(text.substring(index))); 13107 } 13108 break; 13109 } 13110 } 13111 13112 // Concatenating expressions makes it hard to reason about whether some combination of 13113 // concatenated values are unsafe to use and could easily lead to XSS. By requiring that a 13114 // single expression be used for iframe[src], object[src], etc., we ensure that the value 13115 // that's used is assigned or constructed by some JS code somewhere that is more testable or 13116 // make it obvious that you bound the value to some user controlled value. This helps reduce 13117 // the load when auditing for XSS issues. 13118 if (trustedContext && concat.length > 1) { 13119 $interpolateMinErr.throwNoconcat(text); 13120 } 13121 13122 if (!mustHaveExpression || expressions.length) { 13123 var compute = function(values) { 13124 for (var i = 0, ii = expressions.length; i < ii; i++) { 13125 if (allOrNothing && isUndefined(values[i])) return; 13126 concat[expressionPositions[i]] = values[i]; 13127 } 13128 return concat.join(''); 13129 }; 13130 13131 var getValue = function(value) { 13132 return trustedContext ? 13133 $sce.getTrusted(trustedContext, value) : 13134 $sce.valueOf(value); 13135 }; 13136 13137 return extend(function interpolationFn(context) { 13138 var i = 0; 13139 var ii = expressions.length; 13140 var values = new Array(ii); 13141 13142 try { 13143 for (; i < ii; i++) { 13144 values[i] = parseFns[i](context); 13145 } 13146 13147 return compute(values); 13148 } catch (err) { 13149 $exceptionHandler($interpolateMinErr.interr(text, err)); 13150 } 13151 13152 }, { 13153 // all of these properties are undocumented for now 13154 exp: text, //just for compatibility with regular watchers created via $watch 13155 expressions: expressions, 13156 $$watchDelegate: function(scope, listener) { 13157 var lastValue; 13158 return scope.$watchGroup(parseFns, /** @this */ function interpolateFnWatcher(values, oldValues) { 13159 var currValue = compute(values); 13160 if (isFunction(listener)) { 13161 listener.call(this, currValue, values !== oldValues ? lastValue : currValue, scope); 13162 } 13163 lastValue = currValue; 13164 }); 13165 } 13166 }); 13167 } 13168 13169 function parseStringifyInterceptor(value) { 13170 try { 13171 value = getValue(value); 13172 return allOrNothing && !isDefined(value) ? value : stringify(value); 13173 } catch (err) { 13174 $exceptionHandler($interpolateMinErr.interr(text, err)); 13175 } 13176 } 13177 } 13178 13179 13180 /** 13181 * @ngdoc method 13182 * @name $interpolate#startSymbol 13183 * @description 13184 * Symbol to denote the start of expression in the interpolated string. Defaults to `{{`. 13185 * 13186 * Use {@link ng.$interpolateProvider#startSymbol `$interpolateProvider.startSymbol`} to change 13187 * the symbol. 13188 * 13189 * @returns {string} start symbol. 13190 */ 13191 $interpolate.startSymbol = function() { 13192 return startSymbol; 13193 }; 13194 13195 13196 /** 13197 * @ngdoc method 13198 * @name $interpolate#endSymbol 13199 * @description 13200 * Symbol to denote the end of expression in the interpolated string. Defaults to `}}`. 13201 * 13202 * Use {@link ng.$interpolateProvider#endSymbol `$interpolateProvider.endSymbol`} to change 13203 * the symbol. 13204 * 13205 * @returns {string} end symbol. 13206 */ 13207 $interpolate.endSymbol = function() { 13208 return endSymbol; 13209 }; 13210 13211 return $interpolate; 13212 }]; 13213} 13214 13215/** @this */ 13216function $IntervalProvider() { 13217 this.$get = ['$rootScope', '$window', '$q', '$$q', '$browser', 13218 function($rootScope, $window, $q, $$q, $browser) { 13219 var intervals = {}; 13220 13221 13222 /** 13223 * @ngdoc service 13224 * @name $interval 13225 *
13226 * @description 13227 * Angular's wrapper for `window.setInterval`. The `fn` function is executed every `delay` 13228 * milliseconds. 13229 * 13230 * The return value of registering an interval function is a promise. This promise will be 13231 * notified upon each tick of the interval, and will be resolved after `count` iterations, or 13232 * run indefinitely if `count` is not defined. The value of the notification will be the 13233 * number of iterations that have run. 13234 * To cancel an interval, call `$interval.cancel(promise)`. 13235 * 13236 * In tests you can use {@link ngMock.$interval#flush `$interval.flush(millis)`} to 13237 * move forward by `millis` milliseconds and trigger any functions scheduled to run in that 13238 * time. 13239 * 13240 * <div class="alert alert-warning"> 13241 * **Note**: Intervals created by this service must be explicitly destroyed when you are finished 13242 * with them. In particular they are not automatically destroyed when a controller's scope or a 13243 * directive's element are destroyed. 13244 * You should take this into consideration and make sure to always cancel the interval at the 13245 * appropriate moment. See the example below for more details on how and when to do this. 13246 * </div> 13247 * 13248 * @param {function()} fn A function that should be called repeatedly. If no additional arguments 13249 * are passed (see below), the function is called with the current iteration count. 13250 * @param {number} delay Number of milliseconds between each function call. 13251 * @param {number=} [count=0] Number of times to repeat. If not set, or 0, will repeat 13252 * indefinitely. 13253 * @param {boolean=} [invokeApply=true] If set to `false` skips model dirty checking, otherwise 13254 * will invoke `fn` within the {@link ng.$rootScope.Scope#$apply $apply} block. 13255 * @param {...*=} Pass additional parameters to the executed function. 13256 * @returns {promise} A promise which will be notified on each iteration. It will resolve once all iterations of the interval complete. 13257 * 13258 * @example 13259 * <example module="intervalExample" name="interval-service"> 13260 * <file name="index.html"> 13261 * <script> 13262 * angular.module('intervalExample', []) 13263 * .controller('ExampleController', ['$scope', '$interval', 13264 * function($scope, $interval) { 13265 * $scope.format = 'M/d/yy h:mm:ss a'; 13266 * $scope.blood_1 = 100; 13267 * $scope.blood_2 = 120; 13268 * 13269 * var stop; 13270 * $scope.fight = function() { 13271 * // Don't start a new fight if we are already fighting 13272 * if ( angular.isDefined(stop) ) return; 13273 * 13274 * stop = $interval(function() { 13275 * if ($scope.blood_1 > 0 && $scope.blood_2 > 0) { 13276 * $scope.blood_1 = $scope.blood_1 - 3; 13277 * $scope.blood_2 = $scope.blood_2 - 4; 13278 * } else { 13279 * $scope.stopFight(); 13280 * } 13281 * }, 100); 13282 * }; 13283 * 13284 * $scope.stopFight = function() { 13285 * if (angular.isDefined(stop)) { 13286 * $interval.cancel(stop); 13287 * stop = undefined; 13288 * } 13289 * }; 13290 * 13291 * $scope.resetFight = function() { 13292 * $scope.blood_1 = 100; 13293 * $scope.blood_2 = 120; 13294 * }; 13295 * 13296 * $scope.$on('$destroy', function() { 13297 * // Make sure that the interval is destroyed too 13298 * $scope.stopFight(); 13299 * }); 13300 * }]) 13301 * // Register the 'myCurrentTime' directive factory method. 13302 * // We inject $interval and dateFilter service since the factory method is DI. 13303 * .directive('myCurrentTime', ['$interval', 'dateFilter', 13304 * function($interval, dateFilter) { 13305 * // return the directive link function. (compile function not needed) 13306 * return function(scope, element, attrs) { 13307 * var format, // date format 13308 * stopTime; // so that we can cancel the time updates 13309 * 13310 * // used to update the UI 13311 * function updateTime() { 13312 * element.text(dateFilter(new Date(), format)); 13313 * } 13314 * 13315 * // watch the expression, and update the UI on change. 13316 * scope.$watch(attrs.myCurrentTime, function(value) { 13317 * format = value; 13318 * updateTime(); 13319 * }); 13320 * 13321 * stopTime = $interval(updateTime, 1000); 13322 * 13323 * // listen on DOM destroy (removal) event, and cancel the next UI update 13324 * // to prevent updating time after the DOM element was removed. 13325 * element.on('$destroy', function() { 13326 * $interval.cancel(stopTime); 13327 * }); 13328 * } 13329 * }]); 13330 * </script> 13331 * 13332 * <div>
13333 * <div ng-controller="ExampleController"> 13334 * <label>Date format: <input ng-model="format"></label> <hr/> 13335 * Current time is: <span my-current-time="format"></span> 13336 * <hr/> 13337 * Blood 1 : <font color='red'>{{blood_1}}</font> 13338 * Blood 2 : <font color='red'>{{blood_2}}</font> 13339 * <button type="button" data-ng-click="fight()">Fight</button> 13340 * <button type="button" data-ng-click="stopFight()">StopFight</button> 13341 * <button type="button" data-ng-click="resetFight()">resetFight</button> 13342 * </div> 13343 * </div> 13344 * 13345 * </file> 13346 * </example> 13347 */ 13348 function interval(fn, delay, count, invokeApply) { 13349 var hasParams = arguments.length > 4, 13350 args = hasParams ? sliceArgs(arguments, 4) : [], 13351 setInterval = $window.setInterval, 13352 clearInterval = $window.clearInterval, 13353 iteration = 0, 13354 skipApply = (isDefined(invokeApply) && !invokeApply), 13355 deferred = (skipApply ? $$q : $q).defer(), 13356 promise = deferred.promise; 13357 13358 count = isDefined(count) ? count : 0; 13359 13360 promise.$$intervalId = setInterval(function tick() { 13361 if (skipApply) { 13362 $browser.defer(callback); 13363 } else { 13364 $rootScope.$evalAsync(callback); 13365 } 13366 deferred.notify(iteration++); 13367 13368 if (count > 0 && iteration >= count) { 13369 deferred.resolve(iteration); 13370 clearInterval(promise.$$intervalId); 13371 delete intervals[promise.$$intervalId]; 13372 } 13373 13374 if (!skipApply) $rootScope.$apply(); 13375 13376 }, delay); 13377 13378 intervals[promise.$$intervalId] = deferred; 13379 13380 return promise; 13381 13382 function callback() { 13383 if (!hasParams) { 13384 fn(iteration); 13385 } else { 13386 fn.apply(null, args); 13387 } 13388 } 13389 } 13390 13391 13392 /** 13393 * @ngdoc method 13394 * @name $interval#cancel 13395 * 13396 * @description 13397 * Cancels a task associated with the `promise`. 13398 * 13399 * @param {Promise=} promise returned by the `$interval` function. 13400 * @returns {boolean} Returns `true` if the task was successfully canceled. 13401 */ 13402 interval.cancel = function(promise) { 13403 if (promise && promise.$$intervalId in intervals) { 13404 // Interval cancels should not report as unhandled promise. 13405 markQExceptionHandled(intervals[promise.$$intervalId].promise); 13406 intervals[promise.$$intervalId].reject('canceled'); 13407 $window.clearInterval(promise.$$intervalId); 13408 delete intervals[promise.$$intervalId]; 13409 return true; 13410 } 13411 return false; 13412 }; 13413 13414 return interval; 13415 }]; 13416} 13417 13418/** 13419 * @ngdoc service 13420 * @name $jsonpCallbacks 13421 * @requires $window 13422 * @description 13423 * This service handles the lifecycle of callbacks to handle JSONP requests. 13424 * Override this service if you wish to customise where the callbacks are stored and 13425 * how they vary compared to the requested url. 13426 */ 13427var $jsonpCallbacksProvider = /** @this */ function() { 13428 this.$get = function() { 13429 var callbacks = angular.callbacks; 13430 var callbackMap = {}; 13431 13432 function createCallback(callbackId) { 13433 var callback = function(data) { 13434 callback.data = data; 13435 callback.called = true; 13436 }; 13437 callback.id = callbackId; 13438 return callback; 13439 } 13440 13441 return { 13442 /** 13443 * @ngdoc method 13444 * @name $jsonpCallbacks#createCallback 13445 * @param {string} url the url of the JSONP request 13446 * @returns {string} the callback path to send to the server as part of the JSONP request 13447 * @description 13448 * {@link $httpBackend} calls this method to create a callback and get hold of the path to the callback 13449 * to pass to the server, which will be used to call the callback with its payload in the JSONP response. 13450 */ 13451 createCallback: function(url) { 13452 var callbackId = '_' + (callbacks.$$counter++).toString(36); 13453 var callbackPath = 'angular.callbacks.' + callbackId; 13454 var callback = createCallback(callbackId); 13455 callbackMap[callbackPath] = callbacks[callbackId] = callback; 13456 return callbackPath; 13457 }, 13458 /** 13459 * @ngdoc method 13460 * @name $jsonpCallbacks#wasCalled 13461 * @param {string} callbackPath the path to the callback that was sent in the JSONP request 13462 * @returns {boolean} whether the callback has been called, as a result of the JSONP response
vendor: 9,280 bytes, lines 13463-13776
13463 * @description 13464 * {@link $httpBackend} calls this method to find out whether the JSONP response actually called the 13465 * callback that was passed in the request. 13466 */ 13467 wasCalled: function(callbackPath) { 13468 return callbackMap[callbackPath].called; 13469 }, 13470 /** 13471 * @ngdoc method 13472 * @name $jsonpCallbacks#getResponse 13473 * @param {string} callbackPath the path to the callback that was sent in the JSONP request 13474 * @returns {*} the data received from the response via the registered callback 13475 * @description 13476 * {@link $httpBackend} calls this method to get hold of the data that was provided to the callback 13477 * in the JSONP response. 13478 */ 13479 getResponse: function(callbackPath) { 13480 return callbackMap[callbackPath].data; 13481 }, 13482 /** 13483 * @ngdoc method 13484 * @name $jsonpCallbacks#removeCallback 13485 * @param {string} callbackPath the path to the callback that was sent in the JSONP request 13486 * @description 13487 * {@link $httpBackend} calls this method to remove the callback after the JSONP request has 13488 * completed or timed-out. 13489 */ 13490 removeCallback: function(callbackPath) { 13491 var callback = callbackMap[callbackPath]; 13492 delete callbacks[callback.id]; 13493 delete callbackMap[callbackPath]; 13494 } 13495 }; 13496 }; 13497}; 13498 13499/** 13500 * @ngdoc service 13501 * @name $locale 13502 * 13503 * @description 13504 * $locale service provides localization rules for various Angular components. As of right now the 13505 * only public api is: 13506 * 13507 * * `id` – `{string}` – locale id formatted as `languageId-countryId` (e.g. `en-us`) 13508 */ 13509 13510var PATH_MATCH = /^([^?#]*)(\?([^#]*))?(#(.*))?$/, 13511 DEFAULT_PORTS = {'http': 80, 'https': 443, 'ftp': 21}; 13512var $locationMinErr = minErr('$location'); 13513 13514 13515/** 13516 * Encode path using encodeUriSegment, ignoring forward slashes 13517 * 13518 * @param {string} path Path to encode 13519 * @returns {string} 13520 */ 13521function encodePath(path) { 13522 var segments = path.split('/'), 13523 i = segments.length; 13524 13525 while (i--) { 13526 segments[i] = encodeUriSegment(segments[i]); 13527 } 13528 13529 return segments.join('/'); 13530} 13531 13532function parseAbsoluteUrl(absoluteUrl, locationObj) { 13533 var parsedUrl = urlResolve(absoluteUrl); 13534 13535 locationObj.$$protocol = parsedUrl.protocol; 13536 locationObj.$$host = parsedUrl.hostname; 13537 locationObj.$$port = toInt(parsedUrl.port) || DEFAULT_PORTS[parsedUrl.protocol] || null; 13538} 13539 13540var DOUBLE_SLASH_REGEX = /^\s*[\\/]{2,}/; 13541function parseAppUrl(url, locationObj) { 13542 13543 if (DOUBLE_SLASH_REGEX.test(url)) { 13544 throw $locationMinErr('badpath', 'Invalid url "{0}".', url); 13545 } 13546 13547 var prefixed = (url.charAt(0) !== '/'); 13548 if (prefixed) { 13549 url = '/' + url; 13550 } 13551 var match = urlResolve(url); 13552 locationObj.$$path = decodeURIComponent(prefixed && match.pathname.charAt(0) === '/' ? 13553 match.pathname.substring(1) : match.pathname); 13554 locationObj.$$search = parseKeyValue(match.search); 13555 locationObj.$$hash = decodeURIComponent(match.hash); 13556 13557 // make sure path starts with '/'; 13558 if (locationObj.$$path && locationObj.$$path.charAt(0) !== '/') { 13559 locationObj.$$path = '/' + locationObj.$$path; 13560 } 13561} 13562 13563function startsWith(str, search) { 13564 return str.slice(0, search.length) === search; 13565} 13566 13567/** 13568 * 13569 * @param {string} base 13570 * @param {string} url 13571 * @returns {string} returns text from `url` after `base` or `undefined` if it does not begin with 13572 * the expected string. 13573 */ 13574function stripBaseUrl(base, url) { 13575 if (startsWith(url, base)) { 13576 return url.substr(base.length); 13577 } 13578} 13579 13580 13581function stripHash(url) { 13582 var index = url.indexOf('#'); 13583 return index === -1 ? url : url.substr(0, index); 13584} 13585 13586function trimEmptyHash(url) { 13587 return url.replace(/(#.+)|#$/, '$1'); 13588} 13589 13590 13591function stripFile(url) { 13592 return url.substr(0, stripHash(url).lastIndexOf('/') + 1); 13593} 13594 13595/* return the server only (scheme://host:port) */ 13596function serverBase(url) { 13597 return url.substring(0, url.indexOf('/', url.indexOf('//') + 2)); 13598} 13599 13600 13601/** 13602 * LocationHtml5Url represents a URL 13603 * This object is exposed as $location service when HTML5 mode is enabled and supported 13604 * 13605 * @constructor 13606 * @param {string} appBase application base URL 13607 * @param {string} appBaseNoFile application base URL stripped of any filename 13608 * @param {string} basePrefix URL path prefix 13609 */ 13610function LocationHtml5Url(appBase, appBaseNoFile, basePrefix) { 13611 this.$$html5 = true; 13612 basePrefix = basePrefix || ''; 13613 parseAbsoluteUrl(appBase, this); 13614 13615 13616 /** 13617 * Parse given HTML5 (regular) URL string into properties 13618 * @param {string} url HTML5 URL 13619 * @private 13620 */ 13621 this.$$parse = function(url) { 13622 var pathUrl = stripBaseUrl(appBaseNoFile, url); 13623 if (!isString(pathUrl)) { 13624 throw $locationMinErr('ipthprfx', 'Invalid url "{0}", missing path prefix "{1}".', url, 13625 appBaseNoFile); 13626 } 13627 13628 parseAppUrl(pathUrl, this); 13629 13630 if (!this.$$path) { 13631 this.$$path = '/'; 13632 } 13633 13634 this.$$compose(); 13635 }; 13636 13637 /** 13638 * Compose url and update `absUrl` property 13639 * @private 13640 */ 13641 this.$$compose = function() { 13642 var search = toKeyValue(this.$$search), 13643 hash = this.$$hash ? '#' + encodeUriSegment(this.$$hash) : ''; 13644 13645 this.$$url = encodePath(this.$$path) + (search ? '?' + search : '') + hash; 13646 this.$$absUrl = appBaseNoFile + this.$$url.substr(1); // first char is always '/' 13647 13648 this.$$urlUpdatedByLocation = true; 13649 }; 13650 13651 this.$$parseLinkUrl = function(url, relHref) { 13652 if (relHref && relHref[0] === '#') { 13653 // special case for links to hash fragments: 13654 // keep the old url and only replace the hash fragment 13655 this.hash(relHref.slice(1)); 13656 return true; 13657 } 13658 var appUrl, prevAppUrl; 13659 var rewrittenUrl; 13660 13661 13662 if (isDefined(appUrl = stripBaseUrl(appBase, url))) { 13663 prevAppUrl = appUrl; 13664 if (basePrefix && isDefined(appUrl = stripBaseUrl(basePrefix, appUrl))) { 13665 rewrittenUrl = appBaseNoFile + (stripBaseUrl('/', appUrl) || appUrl); 13666 } else { 13667 rewrittenUrl = appBase + prevAppUrl; 13668 } 13669 } else if (isDefined(appUrl = stripBaseUrl(appBaseNoFile, url))) { 13670 rewrittenUrl = appBaseNoFile + appUrl; 13671 } else if (appBaseNoFile === url + '/') { 13672 rewrittenUrl = appBaseNoFile; 13673 } 13674 if (rewrittenUrl) { 13675 this.$$parse(rewrittenUrl); 13676 } 13677 return !!rewrittenUrl; 13678 }; 13679} 13680 13681 13682/** 13683 * LocationHashbangUrl represents URL 13684 * This object is exposed as $location service when developer doesn't opt into html5 mode. 13685 * It also serves as the base class for html5 mode fallback on legacy browsers. 13686 * 13687 * @constructor 13688 * @param {string} appBase application base URL 13689 * @param {string} appBaseNoFile application base URL stripped of any filename 13690 * @param {string} hashPrefix hashbang prefix 13691 */ 13692function LocationHashbangUrl(appBase, appBaseNoFile, hashPrefix) { 13693 13694 parseAbsoluteUrl(appBase, this); 13695 13696 13697 /** 13698 * Parse given hashbang URL into properties 13699 * @param {string} url Hashbang URL 13700 * @private 13701 */ 13702 this.$$parse = function(url) { 13703 var withoutBaseUrl = stripBaseUrl(appBase, url) || stripBaseUrl(appBaseNoFile, url); 13704 var withoutHashUrl; 13705 13706 if (!isUndefined(withoutBaseUrl) && withoutBaseUrl.charAt(0) === '#') { 13707 13708 // The rest of the URL starts with a hash so we have 13709 // got either a hashbang path or a plain hash fragment 13710 withoutHashUrl = stripBaseUrl(hashPrefix, withoutBaseUrl); 13711 if (isUndefined(withoutHashUrl)) { 13712 // There was no hashbang prefix so we just have a hash fragment 13713 withoutHashUrl = withoutBaseUrl; 13714 } 13715 13716 } else { 13717 // There was no hashbang path nor hash fragment: 13718 // If we are in HTML5 mode we use what is left as the path; 13719 // Otherwise we ignore what is left 13720 if (this.$$html5) { 13721 withoutHashUrl = withoutBaseUrl; 13722 } else { 13723 withoutHashUrl = ''; 13724 if (isUndefined(withoutBaseUrl)) { 13725 appBase = url; 13726 /** @type {?} */ (this).replace(); 13727 } 13728 } 13729 } 13730 13731 parseAppUrl(withoutHashUrl, this); 13732 13733 this.$$path = removeWindowsDriveName(this.$$path, withoutHashUrl, appBase); 13734 13735 this.$$compose(); 13736 13737 /* 13738 * In Windows, on an anchor node on documents loaded from 13739 * the filesystem, the browser will return a pathname 13740 * prefixed with the drive name ('/C:/path') when a 13741 * pathname without a drive is set: 13742 * * a.setAttribute('href', '/foo') 13743 * * a.pathname === '/C:/foo' //true 13744 * 13745 * Inside of Angular, we're always using pathnames that 13746 * do not include drive names for routing. 13747 */ 13748 function removeWindowsDriveName(path, url, base) { 13749 /* 13750 Matches paths for file protocol on windows, 13751 such as /C:/foo/bar, and captures only /foo/bar. 13752 */ 13753 var windowsFilePathExp = /^\/[A-Z]:(\/.*)/; 13754 13755 var firstPathSegmentMatch; 13756 13757 //Get the relative path from the input URL. 13758 if (startsWith(url, base)) { 13759 url = url.replace(base, ''); 13760 } 13761 13762 // The input URL intentionally contains a first path segment that ends with a colon. 13763 if (windowsFilePathExp.exec(url)) { 13764 return path; 13765 } 13766 13767 firstPathSegmentMatch = windowsFilePathExp.exec(path); 13768 return firstPathSegmentMatch ? firstPathSegmentMatch[1] : path; 13769 } 13770 }; 13771 13772 /** 13773 * Compose hashbang URL and update `absUrl` property 13774 * @private 13775 */ 13776 this.$$compose = function() {
13777 var search = toKeyValue(this.$$search), 13778 hash = this.$$hash ? '#' + encodeUriSegment(this.$$hash) : ''; 13779 13780 this.$$url = encodePath(this.$$path) + (search ? '?' + search : '') + hash; 13781 this.$$absUrl = appBase + (this.$$url ? hashPrefix + this.$$url : ''); 13782 13783 this.$$urlUpdatedByLocation = true; 13784 }; 13785 13786 this.$$parseLinkUrl = function(url, relHref) { 13787 if (stripHash(appBase) === stripHash(url)) { 13788 this.$$parse(url); 13789 return true; 13790 } 13791 return false; 13792 }; 13793} 13794 13795 13796/** 13797 * LocationHashbangUrl represents URL 13798 * This object is exposed as $location service when html5 history api is enabled but the browser 13799 * does not support it. 13800 * 13801 * @constructor 13802 * @param {string} appBase application base URL 13803 * @param {string} appBaseNoFile application base URL stripped of any filename 13804 * @param {string} hashPrefix hashbang prefix 13805 */ 13806function LocationHashbangInHtml5Url(appBase, appBaseNoFile, hashPrefix) { 13807 this.$$html5 = true; 13808 LocationHashbangUrl.apply(this, arguments); 13809 13810 this.$$parseLinkUrl = function(url, relHref) { 13811 if (relHref && relHref[0] === '#') { 13812 // special case for links to hash fragments: 13813 // keep the old url and only replace the hash fragment 13814 this.hash(relHref.slice(1)); 13815 return true; 13816 } 13817 13818 var rewrittenUrl; 13819 var appUrl; 13820 13821 if (appBase === stripHash(url)) { 13822 rewrittenUrl = url; 13823 } else if ((appUrl = stripBaseUrl(appBaseNoFile, url))) { 13824 rewrittenUrl = appBase + hashPrefix + appUrl; 13825 } else if (appBaseNoFile === url + '/') { 13826 rewrittenUrl = appBaseNoFile; 13827 } 13828 if (rewrittenUrl) { 13829 this.$$parse(rewrittenUrl); 13830 } 13831 return !!rewrittenUrl; 13832 }; 13833 13834 this.$$compose = function() { 13835 var search = toKeyValue(this.$$search), 13836 hash = this.$$hash ? '#' + encodeUriSegment(this.$$hash) : ''; 13837 13838 this.$$url = encodePath(this.$$path) + (search ? '?' + search : '') + hash; 13839 // include hashPrefix in $$absUrl when $$url is empty so IE9 does not reload page because of removal of '#' 13840 this.$$absUrl = appBase + hashPrefix + this.$$url; 13841 13842 this.$$urlUpdatedByLocation = true; 13843 }; 13844 13845} 13846 13847 13848var locationPrototype = { 13849 13850 /** 13851 * Ensure absolute URL is initialized. 13852 * @private 13853 */ 13854 $$absUrl:'', 13855 13856 /** 13857 * Are we in html5 mode? 13858 * @private 13859 */ 13860 $$html5: false, 13861 13862 /** 13863 * Has any change been replacing? 13864 * @private 13865 */ 13866 $$replace: false, 13867 13868 /** 13869 * @ngdoc method 13870 * @name $location#absUrl 13871 * 13872 * @description 13873 * This method is getter only. 13874 * 13875 * Return full URL representation with all segments encoded according to rules specified in 13876 * [RFC 3986](http://www.ietf.org/rfc/rfc3986.txt). 13877 * 13878 * 13879 * ```js 13880 * // given URL http://example.com/#/some/path?foo=bar&baz=xoxo 13881 * var absUrl = $location.absUrl(); 13882 * // => "http://example.com/#/some/path?foo=bar&baz=xoxo" 13883 * ``` 13884 * 13885 * @return {string} full URL 13886 */ 13887 absUrl: locationGetter('$$absUrl'), 13888 13889 /** 13890 * @ngdoc method 13891 * @name $location#url 13892 * 13893 * @description 13894 * This method is getter / setter. 13895 * 13896 * Return URL (e.g. `/path?a=b#hash`) when called without any parameter. 13897 * 13898 * Change path, search and hash, when called with parameter and return `$location`. 13899 * 13900 * 13901 * ```js 13902 * // given URL http://example.com/#/some/path?foo=bar&baz=xoxo 13903 * var url = $location.url(); 13904 * // => "/some/path?foo=bar&baz=xoxo" 13905 * ``` 13906 * 13907 * @param {string=} url New URL without base prefix (e.g. `/path?a=b#hash`) 13908 * @return {string} url 13909 */ 13910 url: function(url) { 13911 if (isUndefined(url)) { 13912 return this.$$url; 13913 } 13914 13915 var match = PATH_MATCH.exec(url); 13916 if (match[1] || url === '') this.path(decodeURIComponent(match[1])); 13917 if (match[2] || match[1] || url === '') this.search(match[3] || ''); 13918 this.hash(match[5] || ''); 13919 13920 return this; 13921 }, 13922 13923 /** 13924 * @ngdoc method 13925 * @name $location#protocol 13926 * 13927 * @description 13928 * This method is getter only. 13929 * 13930 * Return protocol of current URL. 13931 * 13932 * 13933 * ```js 13934 * // given URL http://example.com/#/some/path?foo=bar&baz=xoxo 13935 * var protocol = $location.protocol(); 13936 * // => "http" 13937 * ``` 13938 * 13939 * @return {string} protocol of current URL 13940 */ 13941 protocol: locationGetter('$$protocol'), 13942 13943 /** 13944 * @ngdoc method 13945 * @name $location#host 13946 * 13947 * @description 13948 * This method is getter only. 13949 * 13950 * Return host of current URL. 13951 * 13952 * Note: compared to the non-angular version `location.host` which returns `hostname:port`, this returns the `hostname` portion only. 13953 * 13954 * 13955 * ```js
13956 * // given URL http://example.com/#/some/path?foo=bar&baz=xoxo 13957 * var host = $location.host(); 13958 * // => "example.com" 13959 * 13960 * // given URL http://user:[email protected]:8080/#/some/path?foo=bar&baz=xoxo 13961 * host = $location.host(); 13962 * // => "example.com" 13963 * host = location.host; 13964 * // => "example.com:8080" 13965 * ``` 13966 * 13967 * @return {string} host of current URL. 13968 */ 13969 host: locationGetter('$$host'), 13970 13971 /** 13972 * @ngdoc method 13973 * @name $location#port 13974 * 13975 * @description 13976 * This method is getter only. 13977 * 13978 * Return port of current URL. 13979 * 13980 * 13981 * ```js 13982 * // given URL http://example.com/#/some/path?foo=bar&baz=xoxo 13983 * var port = $location.port(); 13984 * // => 80 13985 * ``` 13986 * 13987 * @return {Number} port 13988 */ 13989 port: locationGetter('$$port'), 13990 13991 /** 13992 * @ngdoc method 13993 * @name $location#path 13994 * 13995 * @description 13996 * This method is getter / setter. 13997 * 13998 * Return path of current URL when called without any parameter. 13999 * 14000 * Change path when called with parameter and return `$location`. 14001 * 14002 * Note: Path should always begin with forward slash (/), this method will add the forward slash 14003 * if it is missing. 14004 * 14005 * 14006 * ```js 14007 * // given URL http://example.com/#/some/path?foo=bar&baz=xoxo 14008 * var path = $location.path(); 14009 * // => "/some/path" 14010 * ``` 14011 * 14012 * @param {(string|number)=} path New path 14013 * @return {(string|object)} path if called with no parameters, or `$location` if called with a parameter 14014 */ 14015 path: locationGetterSetter('$$path', function(path) { 14016 path = path !== null ? path.toString() : ''; 14017 return path.charAt(0) === '/' ? path : '/' + path; 14018 }), 14019 14020 /** 14021 * @ngdoc method 14022 * @name $location#search 14023 * 14024 * @description 14025 * This method is getter / setter. 14026 * 14027 * Return search part (as object) of current URL when called without any parameter. 14028 * 14029 * Change search part when called with parameter and return `$location`. 14030 * 14031 * 14032 * ```js 14033 * // given URL http://example.com/#/some/path?foo=bar&baz=xoxo 14034 * var searchObject = $location.search(); 14035 * // => {foo: 'bar', baz: 'xoxo'} 14036 * 14037 * // set foo to 'yipee' 14038 * $location.search('foo', 'yipee'); 14039 * // $location.search() => {foo: 'yipee', baz: 'xoxo'} 14040 * ``` 14041 * 14042 * @param {string|Object.<string>|Object.<Array.<string>>} search New search params - string or 14043 * hash object. 14044 * 14045 * When called with a single argument the method acts as a setter, setting the `search` component 14046 * of `$location` to the specified value. 14047 * 14048 * If the argument is a hash object containing an array of values, these values will be encoded 14049 * as duplicate search parameters in the URL. 14050 * 14051 * @param {(string|Number|Array<string>|boolean)=} paramValue If `search` is a string or number, then `paramValue` 14052 * will override only a single search property. 14053 * 14054 * If `paramValue` is an array, it will override the property of the `search` component of 14055 * `$location` specified via the first argument. 14056 * 14057 * If `paramValue` is `null`, the property specified via the first argument will be deleted. 14058 * 14059 * If `paramValue` is `true`, the property specified via the first argument will be added with no 14060 * value nor trailing equal sign. 14061 * 14062 * @return {Object} If called with no arguments returns the parsed `search` object. If called with 14063 * one or more arguments returns `$location` object itself. 14064 */ 14065 search: function(search, paramValue) { 14066 switch (arguments.length) { 14067 case 0: 14068 return this.$$search; 14069 case 1: 14070 if (isString(search) || isNumber(search)) { 14071 search = search.toString(); 14072 this.$$search = parseKeyValue(search); 14073 } else if (isObject(search)) { 14074 search = copy(search, {}); 14075 // remove object undefined or null properties 14076 forEach(search, function(value, key) { 14077 if (value == null) delete search[key]; 14078 }); 14079 14080 this.$$search = search; 14081 } else { 14082 throw $locationMinErr('isrcharg', 14083 'The first argument of the `$location#search()` call must be a string or an object.'); 14084 } 14085 break; 14086 default: 14087 if (isUndefined(paramValue) || paramValue === null) { 14088 delete this.$$search[search]; 14089 } else { 14090 this.$$search[search] = paramValue; 14091 } 14092 } 14093 14094 this.$$compose(); 14095 return this; 14096 }, 14097 14098 /** 14099 * @ngdoc method 14100 * @name $location#hash 14101 * 14102 * @description 14103 * This method is getter / setter. 14104 * 14105 * Returns the hash fragment when called without any parameters. 14106 * 14107 * Changes the hash fragment when called with a parameter and returns `$location`. 14108 * 14109 * 14110 * ```js
14111 * // given URL http://example.com/#/some/path?foo=bar&baz=xoxo#hashValue 14112 * var hash = $location.hash(); 14113 * // => "hashValue" 14114 * ``` 14115 * 14116 * @param {(string|number)=} hash New hash fragment 14117 * @return {string} hash 14118 */ 14119 hash: locationGetterSetter('$$hash', function(hash) { 14120 return hash !== null ? hash.toString() : ''; 14121 }), 14122 14123 /** 14124 * @ngdoc method 14125 * @name $location#replace 14126 * 14127 * @description 14128 * If called, all changes to $location during the current `$digest` will replace the current history 14129 * record, instead of adding a new one. 14130 */ 14131 replace: function() { 14132 this.$$replace = true; 14133 return this; 14134 } 14135}; 14136 14137forEach([LocationHashbangInHtml5Url, LocationHashbangUrl, LocationHtml5Url], function(Location) { 14138 Location.prototype = Object.create(locationPrototype); 14139 14140 /** 14141 * @ngdoc method 14142 * @name $location#state 14143 * 14144 * @description 14145 * This method is getter / setter. 14146 * 14147 * Return the history state object when called without any parameter. 14148 * 14149 * Change the history state object when called with one parameter and return `$location`. 14150 * The state object is later passed to `pushState` or `replaceState`. 14151 * 14152 * NOTE: This method is supported only in HTML5 mode and only in browsers supporting 14153 * the HTML5 History API (i.e. methods `pushState` and `replaceState`). If you need to support 14154 * older browsers (like IE9 or Android < 4.0), don't use this method. 14155 * 14156 * @param {object=} state State object for pushState or replaceState 14157 * @return {object} state 14158 */ 14159 Location.prototype.state = function(state) { 14160 if (!arguments.length) { 14161 return this.$$state; 14162 } 14163 14164 if (Location !== LocationHtml5Url || !this.$$html5) { 14165 throw $locationMinErr('nostate', 'History API state support is available only ' + 14166 'in HTML5 mode and only in browsers supporting HTML5 History API'); 14167 } 14168 // The user might modify `stateObject` after invoking `$location.state(stateObject)` 14169 // but we're changing the $$state reference to $browser.state() during the $digest 14170 // so the modification window is narrow. 14171 this.$$state = isUndefined(state) ? null : state; 14172 this.$$urlUpdatedByLocation = true; 14173 14174 return this; 14175 }; 14176}); 14177 14178 14179function locationGetter(property) { 14180 return /** @this */ function() { 14181 return this[property]; 14182 }; 14183} 14184 14185 14186function locationGetterSetter(property, preprocess) { 14187 return /** @this */ function(value) { 14188 if (isUndefined(value)) { 14189 return this[property]; 14190 } 14191 14192 this[property] = preprocess(value); 14193 this.$$compose(); 14194 14195 return this; 14196 }; 14197} 14198 14199 14200/** 14201 * @ngdoc service 14202 * @name $location 14203 * 14204 * @requires $rootElement 14205 * 14206 * @description 14207 * The $location service parses the URL in the browser address bar (based on the 14208 * [window.location](https://developer.mozilla.org/en/window.location)) and makes the URL 14209 * available to your application. Changes to the URL in the address bar are reflected into 14210 * $location service and changes to $location are reflected into the browser address bar. 14211 * 14212 * **The $location service:** 14213 * 14214 * - Exposes the current URL in the browser address bar, so you can 14215 * - Watch and observe the URL. 14216 * - Change the URL. 14217 * - Synchronizes the URL with the browser when the user 14218 * - Changes the address bar. 14219 * - Clicks the back or forward button (or clicks a History link). 14220 * - Clicks on a link. 14221 * - Represents the URL object as a set of methods (protocol, host, port, path, search, hash). 14222 * 14223 * For more information see {@link guide/$location Developer Guide: Using $location} 14224 */ 14225 14226/** 14227 * @ngdoc provider 14228 * @name $locationProvider 14229 * @this 14230 * 14231 * @description 14232 * Use the `$locationProvider` to configure how the application deep linking paths are stored. 14233 */ 14234function $LocationProvider() { 14235 var hashPrefix = '!', 14236 html5Mode = { 14237 enabled: false, 14238 requireBase: true, 14239 rewriteLinks: true 14240 }; 14241 14242 /** 14243 * @ngdoc method 14244 * @name $locationProvider#hashPrefix 14245 * @description 14246 * The default value for the prefix is `'!'`. 14247 * @param {string=} prefix Prefix for hash part (containing path and search) 14248 * @returns {*} current value if used as getter or itself (chaining) if used as setter 14249 */ 14250 this.hashPrefix = function(prefix) { 14251 if (isDefined(prefix)) { 14252 hashPrefix = prefix; 14253 return this; 14254 } else { 14255 return hashPrefix; 14256 } 14257 }; 14258 14259 /** 14260 * @ngdoc method 14261 * @name $locationProvider#html5Mode 14262 * @description 14263 * @param {(boolean|Object)=} mode If boolean, sets `html5Mode.enabled` to value. 14264 * If object, sets `enabled`, `requireBase` and `rewriteLinks` to respective values. Supported 14265 * properties: 14266 * - **enabled** – `{boolean}` – (default: false) If true, will rely on `history.pushState` to 14267 * change urls where supported. Will fall back to hash-prefixed paths in browsers that do not 14268 * support `pushState`. 14269 * - **requireBase** - `{boolean}` - (default: `true`) When html5Mode is enabled, specifies 14270 * whether or not a <base> tag is required to be present. If `enabled` and `requireBase` are 14271 * true, and a base tag is not present, an error will be thrown when `$location` is injected. 14272 * See the {@link guide/$location $location guide for more information} 14273 * - **rewriteLinks** - `{boolean|string}` - (default: `true`) When html5Mode is enabled, 14274 * enables/disables URL rewriting for relative links. If set to a string, URL rewriting will 14275 * only happen on links with an attribute that matches the given string. For example, if set 14276 * to `'internal-link'`, then the URL will only be rewritten for `<a internal-link>` links. 14277 * Note that [attribute name normalization](guide/directive#normalization) does not apply 14278 * here, so `'internalLink'` will **not** match `'internal-link'`. 14279 * 14280 * @returns {Object} html5Mode object if used as getter or itself (chaining) if used as setter 14281 */ 14282 this.html5Mode = function(mode) { 14283 if (isBoolean(mode)) { 14284 html5Mode.enabled = mode; 14285 return this; 14286 } else if (isObject(mode)) { 14287 14288 if (isBoolean(mode.enabled)) { 14289 html5Mode.enabled = mode.enabled; 14290 } 14291 14292 if (isBoolean(mode.requireBase)) { 14293 html5Mode.requireBase = mode.requireBase; 14294 } 14295 14296 if (isBoolean(mode.rewriteLinks) || isString(mode.rewriteLinks)) { 14297 html5Mode.rewriteLinks = mode.rewriteLinks; 14298 } 14299 14300 return this; 14301 } else { 14302 return html5Mode; 14303 } 14304 }; 14305 14306 /** 14307 * @ngdoc event 14308 * @name $location#$locationChangeStart 14309 * @eventType broadcast on root scope 14310 * @description 14311 * Broadcasted before a URL will change. 14312 * 14313 * This change can be prevented by calling 14314 * `preventDefault` method of the event. See {@link ng.$rootScope.Scope#$on} for more 14315 * details about event object. Upon successful change 14316 * {@link ng.$location#$locationChangeSuccess $locationChangeSuccess} is fired. 14317 * 14318 * The `newState` and `oldState` parameters may be defined only in HTML5 mode and when 14319 * the browser supports the HTML5 History API. 14320 * 14321 * @param {Object} angularEvent Synthetic event object. 14322 * @param {string} newUrl New URL 14323 * @param {string=} oldUrl URL that was before it was changed. 14324 * @param {string=} newState New history state object 14325 * @param {string=} oldState History state object that was before it was changed. 14326 */ 14327 14328 /** 14329 * @ngdoc event 14330 * @name $location#$locationChangeSuccess 14331 * @eventType broadcast on root scope 14332 * @description 14333 * Broadcasted after a URL was changed. 14334 * 14335 * The `newState` and `oldState` parameters may be defined only in HTML5 mode and when 14336 * the browser supports the HTML5 History API. 14337 * 14338 * @param {Object} angularEvent Synthetic event object. 14339 * @param {string} newUrl New URL 14340 * @param {string=} oldUrl URL that was before it was changed. 14341 * @param {string=} newState New history state object 14342 * @param {string=} oldState History state object that was before it was changed. 14343 */ 14344 14345 this.$get = ['$rootScope', '$browser', '$sniffer', '$rootElement', '$window', 14346 function($rootScope, $browser, $sniffer, $rootElement, $window) { 14347 var $location, 14348 LocationMode, 14349 baseHref = $browser.baseHref(), // if base[href] is undefined, it defaults to '' 14350 initialUrl = $browser.url(), 14351 appBase; 14352 14353 if (html5Mode.enabled) { 14354 if (!baseHref && html5Mode.requireBase) { 14355 throw $locationMinErr('nobase', 14356 '$location in HTML5 mode requires a <base> tag to be present!'); 14357 } 14358 appBase = serverBase(initialUrl) + (baseHref || '/'); 14359 LocationMode = $sniffer.history ? LocationHtml5Url : LocationHashbangInHtml5Url; 14360 } else { 14361 appBase = stripHash(initialUrl); 14362 LocationMode = LocationHashbangUrl; 14363 } 14364 var appBaseNoFile = stripFile(appBase); 14365
vendor: 12,480 bytes, lines 14366-14726
14366 $location = new LocationMode(appBase, appBaseNoFile, '#' + hashPrefix); 14367 $location.$$parseLinkUrl(initialUrl, initialUrl); 14368 14369 $location.$$state = $browser.state(); 14370 14371 var IGNORE_URI_REGEXP = /^\s*(javascript|mailto):/i; 14372 14373 function setBrowserUrlWithFallback(url, replace, state) { 14374 var oldUrl = $location.url(); 14375 var oldState = $location.$$state; 14376 try { 14377 $browser.url(url, replace, state); 14378 14379 // Make sure $location.state() returns referentially identical (not just deeply equal) 14380 // state object; this makes possible quick checking if the state changed in the digest 14381 // loop. Checking deep equality would be too expensive. 14382 $location.$$state = $browser.state(); 14383 } catch (e) { 14384 // Restore old values if pushState fails 14385 $location.url(oldUrl); 14386 $location.$$state = oldState; 14387 14388 throw e; 14389 } 14390 } 14391 14392 $rootElement.on('click', function(event) { 14393 var rewriteLinks = html5Mode.rewriteLinks; 14394 // TODO(vojta): rewrite link when opening in new tab/window (in legacy browser) 14395 // currently we open nice url link and redirect then 14396 14397 if (!rewriteLinks || event.ctrlKey || event.metaKey || event.shiftKey || event.which === 2 || event.button === 2) return; 14398 14399 var elm = jqLite(event.target); 14400 14401 // traverse the DOM up to find first A tag 14402 while (nodeName_(elm[0]) !== 'a') { 14403 // ignore rewriting if no A tag (reached root element, or no parent - removed from document) 14404 if (elm[0] === $rootElement[0] || !(elm = elm.parent())[0]) return; 14405 } 14406 14407 if (isString(rewriteLinks) && isUndefined(elm.attr(rewriteLinks))) return; 14408 14409 var absHref = elm.prop('href'); 14410 // get the actual href attribute - see 14411 // http://msdn.microsoft.com/en-us/library/ie/dd347148(v=vs.85).aspx 14412 var relHref = elm.attr('href') || elm.attr('xlink:href'); 14413 14414 if (isObject(absHref) && absHref.toString() === '[object SVGAnimatedString]') { 14415 // SVGAnimatedString.animVal should be identical to SVGAnimatedString.baseVal, unless during 14416 // an animation. 14417 absHref = urlResolve(absHref.animVal).href; 14418 } 14419 14420 // Ignore when url is started with javascript: or mailto: 14421 if (IGNORE_URI_REGEXP.test(absHref)) return; 14422 14423 if (absHref && !elm.attr('target') && !event.isDefaultPrevented()) { 14424 if ($location.$$parseLinkUrl(absHref, relHref)) { 14425 // We do a preventDefault for all urls that are part of the angular application, 14426 // in html5mode and also without, so that we are able to abort navigation without 14427 // getting double entries in the location history. 14428 event.preventDefault(); 14429 // update location manually 14430 if ($location.absUrl() !== $browser.url()) { 14431 $rootScope.$apply(); 14432 // hack to work around FF6 bug 684208 when scenario runner clicks on links 14433 $window.angular['ff-684208-preventDefault'] = true; 14434 } 14435 } 14436 } 14437 }); 14438 14439 14440 // rewrite hashbang url <> html5 url 14441 if (trimEmptyHash($location.absUrl()) !== trimEmptyHash(initialUrl)) { 14442 $browser.url($location.absUrl(), true); 14443 } 14444 14445 var initializing = true; 14446 14447 // update $location when $browser url changes 14448 $browser.onUrlChange(function(newUrl, newState) { 14449 14450 if (!startsWith(newUrl, appBaseNoFile)) { 14451 // If we are navigating outside of the app then force a reload 14452 $window.location.href = newUrl; 14453 return; 14454 } 14455 14456 $rootScope.$evalAsync(function() { 14457 var oldUrl = $location.absUrl(); 14458 var oldState = $location.$$state; 14459 var defaultPrevented; 14460 newUrl = trimEmptyHash(newUrl); 14461 $location.$$parse(newUrl); 14462 $location.$$state = newState; 14463 14464 defaultPrevented = $rootScope.$broadcast('$locationChangeStart', newUrl, oldUrl, 14465 newState, oldState).defaultPrevented; 14466 14467 // if the location was changed by a `$locationChangeStart` handler then stop 14468 // processing this location change 14469 if ($location.absUrl() !== newUrl) return; 14470 14471 if (defaultPrevented) { 14472 $location.$$parse(oldUrl); 14473 $location.$$state = oldState; 14474 setBrowserUrlWithFallback(oldUrl, false, oldState); 14475 } else { 14476 initializing = false; 14477 afterLocationChange(oldUrl, oldState); 14478 } 14479 }); 14480 if (!$rootScope.$$phase) $rootScope.$digest(); 14481 }); 14482 14483 // update browser 14484 $rootScope.$watch(function $locationWatch() { 14485 if (initializing || $location.$$urlUpdatedByLocation) { 14486 $location.$$urlUpdatedByLocation = false; 14487 14488 var oldUrl = trimEmptyHash($browser.url()); 14489 var newUrl = trimEmptyHash($location.absUrl()); 14490 var oldState = $browser.state(); 14491 var currentReplace = $location.$$replace; 14492 var urlOrStateChanged = oldUrl !== newUrl || 14493 ($location.$$html5 && $sniffer.history && oldState !== $location.$$state); 14494 14495 if (initializing || urlOrStateChanged) { 14496 initializing = false; 14497 14498 $rootScope.$evalAsync(function() { 14499 var newUrl = $location.absUrl(); 14500 var defaultPrevented = $rootScope.$broadcast('$locationChangeStart', newUrl, oldUrl, 14501 $location.$$state, oldState).defaultPrevented; 14502 14503 // if the location was changed by a `$locationChangeStart` handler then stop 14504 // processing this location change 14505 if ($location.absUrl() !== newUrl) return; 14506 14507 if (defaultPrevented) { 14508 $location.$$parse(oldUrl); 14509 $location.$$state = oldState; 14510 } else { 14511 if (urlOrStateChanged) { 14512 setBrowserUrlWithFallback(newUrl, currentReplace, 14513 oldState === $location.$$state ? null : $location.$$state); 14514 } 14515 afterLocationChange(oldUrl, oldState); 14516 } 14517 }); 14518 } 14519 } 14520 14521 $location.$$replace = false; 14522 14523 // we don't need to return anything because $evalAsync will make the digest loop dirty when 14524 // there is a change 14525 }); 14526 14527 return $location; 14528 14529 function afterLocationChange(oldUrl, oldState) { 14530 $rootScope.$broadcast('$locationChangeSuccess', $location.absUrl(), oldUrl, 14531 $location.$$state, oldState); 14532 } 14533}]; 14534} 14535 14536/** 14537 * @ngdoc service 14538 * @name $log 14539 * @requires $window 14540 * 14541 * @description 14542 * Simple service for logging. Default implementation safely writes the message 14543 * into the browser's console (if present). 14544 * 14545 * The main purpose of this service is to simplify debugging and troubleshooting. 14546 * 14547 * To reveal the location of the calls to `$log` in the JavaScript console, 14548 * you can "blackbox" the AngularJS source in your browser: 14549 * 14550 * [Mozilla description of blackboxing](https://developer.mozilla.org/en-US/docs/Tools/Debugger/How_to/Black_box_a_source). 14551 * [Chrome description of blackboxing](https://developer.chrome.com/devtools/docs/blackboxing). 14552 * 14553 * Note: Not all browsers support blackboxing. 14554 * 14555 * The default is to log `debug` messages. You can use 14556 * {@link ng.$logProvider ng.$logProvider#debugEnabled} to change this. 14557 * 14558 * @example 14559 <example module="logExample" name="log-service"> 14560 <file name="script.js"> 14561 angular.module('logExample', []) 14562 .controller('LogController', ['$scope', '$log', function($scope, $log) { 14563 $scope.$log = $log; 14564 $scope.message = 'Hello World!'; 14565 }]); 14566 </file> 14567 <file name="index.html"> 14568 <div ng-controller="LogController"> 14569 <p>Reload this page with open console, enter text and hit the log button...</p> 14570 <label>Message: 14571 <input type="text" ng-model="message" /></label> 14572 <button ng-click="$log.log(message)">log</button> 14573 <button ng-click="$log.warn(message)">warn</button> 14574 <button ng-click="$log.info(message)">info</button> 14575 <button ng-click="$log.error(message)">error</button> 14576 <button ng-click="$log.debug(message)">debug</button> 14577 </div> 14578 </file> 14579 </example> 14580 */ 14581 14582/** 14583 * @ngdoc provider 14584 * @name $logProvider 14585 * @this 14586 * 14587 * @description 14588 * Use the `$logProvider` to configure how the application logs messages 14589 */ 14590function $LogProvider() { 14591 var debug = true, 14592 self = this; 14593 14594 /** 14595 * @ngdoc method 14596 * @name $logProvider#debugEnabled 14597 * @description 14598 * @param {boolean=} flag enable or disable debug level messages 14599 * @returns {*} current value if used as getter or itself (chaining) if used as setter 14600 */ 14601 this.debugEnabled = function(flag) { 14602 if (isDefined(flag)) { 14603 debug = flag; 14604 return this; 14605 } else { 14606 return debug; 14607 } 14608 }; 14609 14610 this.$get = ['$window', function($window) { 14611 // Support: IE 9-11, Edge 12-14+ 14612 // IE/Edge display errors in such a way that it requires the user to click in 4 places 14613 // to see the stack trace. There is no way to feature-detect it so there's a chance 14614 // of the user agent sniffing to go wrong but since it's only about logging, this shouldn't 14615 // break apps. Other browsers display errors in a sensible way and some of them map stack 14616 // traces along source maps if available so it makes sense to let browsers display it 14617 // as they want. 14618 var formatStackTrace = msie || /\bEdge\//.test($window.navigator && $window.navigator.userAgent); 14619 14620 return { 14621 /** 14622 * @ngdoc method 14623 * @name $log#log 14624 * 14625 * @description 14626 * Write a log message 14627 */ 14628 log: consoleLog('log'), 14629 14630 /** 14631 * @ngdoc method 14632 * @name $log#info 14633 * 14634 * @description 14635 * Write an information message 14636 */ 14637 info: consoleLog('info'), 14638 14639 /** 14640 * @ngdoc method 14641 * @name $log#warn 14642 * 14643 * @description 14644 * Write a warning message 14645 */ 14646 warn: consoleLog('warn'), 14647 14648 /** 14649 * @ngdoc method 14650 * @name $log#error 14651 * 14652 * @description 14653 * Write an error message 14654 */ 14655 error: consoleLog('error'), 14656 14657 /** 14658 * @ngdoc method 14659 * @name $log#debug 14660 * 14661 * @description 14662 * Write a debug message 14663 */ 14664 debug: (function() { 14665 var fn = consoleLog('debug'); 14666 14667 return function() { 14668 if (debug) { 14669 fn.apply(self, arguments); 14670 } 14671 }; 14672 })() 14673 }; 14674 14675 function formatError(arg) { 14676 if (isError(arg)) { 14677 if (arg.stack && formatStackTrace) { 14678 arg = (arg.message && arg.stack.indexOf(arg.message) === -1) 14679 ? 'Error: ' + arg.message + '\n' + arg.stack 14680 : arg.stack; 14681 } else if (arg.sourceURL) { 14682 arg = arg.message + '\n' + arg.sourceURL + ':' + arg.line; 14683 } 14684 } 14685 return arg; 14686 } 14687 14688 function consoleLog(type) { 14689 var console = $window.console || {}, 14690 logFn = console[type] || console.log || noop; 14691 14692 return function() { 14693 var args = []; 14694 forEach(arguments, function(arg) { 14695 args.push(formatError(arg)); 14696 }); 14697 // Support: IE 9 only 14698 // console methods don't inherit from Function.prototype in IE 9 so we can't 14699 // call `logFn.apply(console, args)` directly. 14700 return Function.prototype.apply.call(logFn, console, args); 14701 }; 14702 } 14703 }]; 14704} 14705 14706/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * 14707 * Any commits to this file should be reviewed with security in mind. * 14708 * Changes to this file can potentially create security vulnerabilities. * 14709 * An approval from 2 Core members with history of modifying * 14710 * this file is required. * 14711 * * 14712 * Does the change somehow allow for arbitrary javascript to be executed? * 14713 * Or allows for someone to change the prototype of built-in objects? * 14714 * Or gives undesired access to variables likes document or window? * 14715 * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ 14716 14717var $parseMinErr = minErr('$parse'); 14718 14719var objectValueOf = {}.constructor.prototype.valueOf; 14720 14721// Sandboxing Angular Expressions 14722// ------------------------------ 14723// Angular expressions are no longer sandboxed. So it is now even easier to access arbitrary JS code by 14724// various means such as obtaining a reference to native JS functions like the Function constructor. 14725// 14726// As an example, consider the following Angular
vendor: 51,685 bytes, lines 14726-16350
14726 expression: 14727// 14728// {}.toString.constructor('alert("evil JS code")') 14729// 14730// It is important to realize that if you create an expression from a string that contains user provided 14731// content then it is possible that your application contains a security vulnerability to an XSS style attack. 14732// 14733// See https://docs.angularjs.org/guide/security 14734 14735 14736function getStringValue(name) { 14737 // Property names must be strings. This means that non-string objects cannot be used 14738 // as keys in an object. Any non-string object, including a number, is typecasted 14739 // into a string via the toString method. 14740 // -- MDN, https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Operators/Property_accessors#Property_names 14741 // 14742 // So, to ensure that we are checking the same `name` that JavaScript would use, we cast it 14743 // to a string. It's not always possible. If `name` is an object and its `toString` method is 14744 // 'broken' (doesn't return a string, isn't a function, etc.), an error will be thrown: 14745 // 14746 // TypeError: Cannot convert object to primitive value 14747 // 14748 // For performance reasons, we don't catch this error here and allow it to propagate up the call 14749 // stack. Note that you'll get the same error in JavaScript if you try to access a property using 14750 // such a 'broken' object as a key. 14751 return name + ''; 14752} 14753 14754 14755var OPERATORS = createMap(); 14756forEach('+ - * / % === !== == != < > <= >= && || ! = |'.split(' '), function(operator) { OPERATORS[operator] = true; }); 14757var ESCAPE = {'n':'\n', 'f':'\f', 'r':'\r', 't':'\t', 'v':'\v', '\'':'\'', '"':'"'}; 14758 14759 14760///////////////////////////////////////// 14761 14762 14763/** 14764 * @constructor 14765 */ 14766var Lexer = function Lexer(options) { 14767 this.options = options; 14768}; 14769 14770Lexer.prototype = { 14771 constructor: Lexer, 14772 14773 lex: function(text) { 14774 this.text = text; 14775 this.index = 0; 14776 this.tokens = []; 14777 14778 while (this.index < this.text.length) { 14779 var ch = this.text.charAt(this.index); 14780 if (ch === '"' || ch === '\'') { 14781 this.readString(ch); 14782 } else if (this.isNumber(ch) || ch === '.' && this.isNumber(this.peek())) { 14783 this.readNumber(); 14784 } else if (this.isIdentifierStart(this.peekMultichar())) { 14785 this.readIdent(); 14786 } else if (this.is(ch, '(){}[].,;:?')) { 14787 this.tokens.push({index: this.index, text: ch}); 14788 this.index++; 14789 } else if (this.isWhitespace(ch)) { 14790 this.index++; 14791 } else { 14792 var ch2 = ch + this.peek(); 14793 var ch3 = ch2 + this.peek(2); 14794 var op1 = OPERATORS[ch]; 14795 var op2 = OPERATORS[ch2]; 14796 var op3 = OPERATORS[ch3]; 14797 if (op1 || op2 || op3) { 14798 var token = op3 ? ch3 : (op2 ? ch2 : ch); 14799 this.tokens.push({index: this.index, text: token, operator: true}); 14800 this.index += token.length; 14801 } else { 14802 this.throwError('Unexpected next character ', this.index, this.index + 1); 14803 } 14804 } 14805 } 14806 return this.tokens; 14807 }, 14808 14809 is: function(ch, chars) { 14810 return chars.indexOf(ch) !== -1; 14811 }, 14812 14813 peek: function(i) { 14814 var num = i || 1; 14815 return (this.index + num < this.text.length) ? this.text.charAt(this.index + num) : false; 14816 }, 14817 14818 isNumber: function(ch) { 14819 return ('0' <= ch && ch <= '9') && typeof ch === 'string'; 14820 }, 14821 14822 isWhitespace: function(ch) { 14823 // IE treats non-breaking space as \u00A0 14824 return (ch === ' ' || ch === '\r' || ch === '\t' || 14825 ch === '\n' || ch === '\v' || ch === '\u00A0'); 14826 }, 14827 14828 isIdentifierStart: function(ch) { 14829 return this.options.isIdentifierStart ? 14830 this.options.isIdentifierStart(ch, this.codePointAt(ch)) : 14831 this.isValidIdentifierStart(ch); 14832 }, 14833 14834 isValidIdentifierStart: function(ch) { 14835 return ('a' <= ch && ch <= 'z' || 14836 'A' <= ch && ch <= 'Z' || 14837 '_' === ch || ch === '$'); 14838 }, 14839 14840 isIdentifierContinue: function(ch) { 14841 return this.options.isIdentifierContinue ? 14842 this.options.isIdentifierContinue(ch, this.codePointAt(ch)) : 14843 this.isValidIdentifierContinue(ch); 14844 }, 14845 14846 isValidIdentifierContinue: function(ch, cp) { 14847 return this.isValidIdentifierStart(ch, cp) || this.isNumber(ch); 14848 }, 14849 14850 codePointAt: function(ch) { 14851 if (ch.length === 1) return ch.charCodeAt(0); 14852 // eslint-disable-next-line no-bitwise 14853 return (ch.charCodeAt(0) << 10) + ch.charCodeAt(1) - 0x35FDC00; 14854 }, 14855 14856 peekMultichar: function() { 14857 var ch = this.text.charAt(this.index); 14858 var peek = this.peek(); 14859 if (!peek) { 14860 return ch; 14861 } 14862 var cp1 = ch.charCodeAt(0); 14863 var cp2 = peek.charCodeAt(0); 14864 if (cp1 >= 0xD800 && cp1 <= 0xDBFF && cp2 >= 0xDC00 && cp2 <= 0xDFFF) { 14865 return ch + peek; 14866 } 14867 return ch; 14868 }, 14869 14870 isExpOperator: function(ch) { 14871 return (ch === '-' || ch === '+' || this.isNumber(ch)); 14872 }, 14873 14874 throwError: function(error, start, end) { 14875 end = end || this.index; 14876 var colStr = (isDefined(start) 14877 ? 's ' + start + '-' + this.index + ' [' + this.text.substring(start, end) + ']' 14878 : ' ' + end); 14879 throw $parseMinErr('lexerr', 'Lexer Error: {0} at column{1} in expression [{2}].', 14880 error, colStr, this.text); 14881 }, 14882 14883 readNumber: function() { 14884 var number = ''; 14885 var start = this.index; 14886 while (this.index < this.text.length) { 14887 var ch = lowercase(this.text.charAt(this.index)); 14888 if (ch === '.' || this.isNumber(ch)) { 14889 number += ch; 14890 } else { 14891 var peekCh = this.peek(); 14892 if (ch === 'e' && this.isExpOperator(peekCh)) { 14893 number += ch; 14894 } else if (this.isExpOperator(ch) && 14895 peekCh && this.isNumber(peekCh) && 14896 number.charAt(number.length - 1) === 'e') { 14897 number += ch; 14898 } else if (this.isExpOperator(ch) && 14899 (!peekCh || !this.isNumber(peekCh)) && 14900 number.charAt(number.length - 1) === 'e') { 14901 this.throwError('Invalid exponent'); 14902 } else { 14903 break; 14904 } 14905 } 14906 this.index++; 14907 } 14908 this.tokens.push({ 14909 index: start, 14910 text: number, 14911 constant: true, 14912 value: Number(number) 14913 }); 14914 }, 14915 14916 readIdent: function() { 14917 var start = this.index; 14918 this.index += this.peekMultichar().length; 14919 while (this.index < this.text.length) { 14920 var ch = this.peekMultichar(); 14921 if (!this.isIdentifierContinue(ch)) { 14922 break; 14923 } 14924 this.index += ch.length; 14925 } 14926 this.tokens.push({ 14927 index: start, 14928 text: this.text.slice(start, this.index), 14929 identifier: true 14930 }); 14931 }, 14932 14933 readString: function(quote) { 14934 var start = this.index; 14935 this.index++; 14936 var string = ''; 14937 var rawString = quote; 14938 var escape = false; 14939 while (this.index < this.text.length) { 14940 var ch = this.text.charAt(this.index); 14941 rawString += ch; 14942 if (escape) { 14943 if (ch === 'u') { 14944 var hex = this.text.substring(this.index + 1, this.index + 5); 14945 if (!hex.match(/[\da-f]{4}/i)) { 14946 this.throwError('Invalid unicode escape [\\u' + hex + ']'); 14947 } 14948 this.index += 4; 14949 string += String.fromCharCode(parseInt(hex, 16)); 14950 } else { 14951 var rep = ESCAPE[ch]; 14952 string = string + (rep || ch); 14953 } 14954 escape = false; 14955 } else if (ch === '\\') { 14956 escape = true; 14957 } else if (ch === quote) { 14958 this.index++; 14959 this.tokens.push({ 14960 index: start, 14961 text: rawString, 14962 constant: true, 14963 value: string 14964 }); 14965 return; 14966 } else { 14967 string += ch; 14968 } 14969 this.index++; 14970 } 14971 this.throwError('Unterminated quote', start); 14972 } 14973}; 14974 14975var AST = function AST(lexer, options) { 14976 this.lexer = lexer; 14977 this.options = options; 14978}; 14979 14980AST.Program = 'Program'; 14981AST.ExpressionStatement = 'ExpressionStatement'; 14982AST.AssignmentExpression = 'AssignmentExpression'; 14983AST.ConditionalExpression = 'ConditionalExpression'; 14984AST.LogicalExpression = 'LogicalExpression'; 14985AST.BinaryExpression = 'BinaryExpression'; 14986AST.UnaryExpression = 'UnaryExpression'; 14987AST.CallExpression = 'CallExpression'; 14988AST.MemberExpression = 'MemberExpression'; 14989AST.Identifier = 'Identifier'; 14990AST.Literal = 'Literal'; 14991AST.ArrayExpression = 'ArrayExpression'; 14992AST.Property = 'Property'; 14993AST.ObjectExpression = 'ObjectExpression'; 14994AST.ThisExpression = 'ThisExpression'; 14995AST.LocalsExpression = 'LocalsExpression'; 14996 14997// Internal use only 14998AST.NGValueParameter = 'NGValueParameter'; 14999 15000AST.prototype = { 15001 ast: function(text) { 15002 this.text = text; 15003 this.tokens = this.lexer.lex(text); 15004 15005 var value = this.program(); 15006 15007 if (this.tokens.length !== 0) { 15008 this.throwError('is an unexpected token', this.tokens[0]); 15009 } 15010 15011 return value; 15012 }, 15013 15014 program: function() { 15015 var body = []; 15016 while (true) { 15017 if (this.tokens.length > 0 && !this.peek('}', ')', ';', ']')) 15018 body.push(this.expressionStatement()); 15019 if (!this.expect(';')) { 15020 return { type: AST.Program, body: body}; 15021 } 15022 } 15023 }, 15024 15025 expressionStatement: function() { 15026 return { type: AST.ExpressionStatement, expression: this.filterChain() }; 15027 }, 15028 15029 filterChain: function() { 15030 var left = this.expression(); 15031 while (this.expect('|')) { 15032 left = this.filter(left); 15033 } 15034 return left; 15035 }, 15036 15037 expression: function() { 15038 return this.assignment(); 15039 }, 15040 15041 assignment: function() { 15042 var result = this.ternary(); 15043 if (this.expect('=')) { 15044 if (!isAssignable(result)) { 15045 throw $parseMinErr('lval', 'Trying to assign a value to a non l-value'); 15046 } 15047 15048 result = { type: AST.AssignmentExpression, left: result, right: this.assignment(), operator: '='}; 15049 } 15050 return result; 15051 }, 15052 15053 ternary: function() { 15054 var test = this.logicalOR(); 15055 var alternate; 15056 var consequent; 15057 if (this.expect('?')) { 15058 alternate = this.expression(); 15059 if (this.consume(':')) { 15060 consequent = this.expression(); 15061 return { type: AST.ConditionalExpression, test: test, alternate: alternate, consequent: consequent}; 15062 } 15063 } 15064 return test; 15065 }, 15066 15067 logicalOR: function() { 15068 var left = this.logicalAND(); 15069 while (this.expect('||')) { 15070 left = { type: AST.LogicalExpression, operator: '||', left: left, right: this.logicalAND() }; 15071 } 15072 return left; 15073 }, 15074 15075 logicalAND: function() { 15076 var left = this.equality(); 15077 while (this.expect('&&')) { 15078 left = { type: AST.LogicalExpression, operator: '&&', left: left, right: this.equality()}; 15079 } 15080 return left; 15081 }, 15082 15083 equality: function() { 15084 var left = this.relational(); 15085 var token; 15086 while ((token = this.expect('==','!=','===','!=='))) { 15087 left = { type: AST.BinaryExpression, operator: token.text, left: left, right: this.relational() }; 15088 } 15089 return left; 15090 }, 15091 15092 relational: function() { 15093 var left = this.additive(); 15094 var token; 15095 while ((token = this.expect('<', '>', '<=', '>='))) { 15096 left = { type: AST.BinaryExpression, operator: token.text, left: left, right: this.additive() }; 15097 } 15098 return left; 15099 }, 15100 15101 additive: function() { 15102 var left = this.multiplicative(); 15103 var token; 15104 while ((token = this.expect('+','-'))) { 15105 left = { type: AST.BinaryExpression, operator: token.text, left: left, right: this.multiplicative() }; 15106 } 15107 return left; 15108 }, 15109 15110 multiplicative: function() { 15111 var left = this.unary(); 15112 var token; 15113 while ((token = this.expect('*','/','%'))) { 15114 left = { type: AST.BinaryExpression, operator: token.text, left: left, right: this.unary() }; 15115 } 15116 return left; 15117 }, 15118 15119 unary: function() { 15120 var token; 15121 if ((token = this.expect('+', '-', '!'))) { 15122 return { type: AST.UnaryExpression, operator: token.text, prefix: true, argument: this.unary() }; 15123 } else { 15124 return this.primary(); 15125 } 15126 }, 15127 15128 primary: function() { 15129 var primary; 15130 if (this.expect('(')) { 15131 primary = this.filterChain(); 15132 this.consume(')'); 15133 } else if (this.expect('[')) { 15134 primary = this.arrayDeclaration(); 15135 } else if (this.expect('{')) { 15136 primary = this.object(); 15137 } else if (this.selfReferential.hasOwnProperty(this.peek().text)) { 15138 primary = copy(this.selfReferential[this.consume().text]); 15139 } else if (this.options.literals.hasOwnProperty(this.peek().text)) { 15140 primary = { type: AST.Literal, value: this.options.literals[this.consume().text]}; 15141 } else if (this.peek().identifier) { 15142 primary = this.identifier(); 15143 } else if (this.peek().constant) { 15144 primary = this.constant(); 15145 } else { 15146 this.throwError('not a primary expression', this.peek()); 15147 } 15148 15149 var next; 15150 while ((next = this.expect('(', '[', '.'))) { 15151 if (next.text === '(') { 15152 primary = {type: AST.CallExpression, callee: primary, arguments: this.parseArguments() }; 15153 this.consume(')'); 15154 } else if (next.text === '[') { 15155 primary = { type: AST.MemberExpression, object: primary, property: this.expression(), computed: true }; 15156 this.consume(']'); 15157 } else if (next.text === '.') { 15158 primary = { type: AST.MemberExpression, object: primary, property: this.identifier(), computed: false }; 15159 } else { 15160 this.throwError('IMPOSSIBLE'); 15161 } 15162 } 15163 return primary; 15164 }, 15165 15166 filter: function(baseExpression) { 15167 var args = [baseExpression]; 15168 var result = {type: AST.CallExpression, callee: this.identifier(), arguments: args, filter: true}; 15169 15170 while (this.expect(':')) { 15171 args.push(this.expression()); 15172 } 15173 15174 return result; 15175 }, 15176 15177 parseArguments: function() { 15178 var args = []; 15179 if (this.peekToken().text !== ')') { 15180 do { 15181 args.push(this.filterChain()); 15182 } while (this.expect(',')); 15183 } 15184 return args; 15185 }, 15186 15187 identifier: function() { 15188 var token = this.consume(); 15189 if (!token.identifier) { 15190 this.throwError('is not a valid identifier', token); 15191 } 15192 return { type: AST.Identifier, name: token.text }; 15193 }, 15194 15195 constant: function() { 15196 // TODO check that it is a constant 15197 return { type: AST.Literal, value: this.consume().value }; 15198 }, 15199 15200 arrayDeclaration: function() { 15201 var elements = []; 15202 if (this.peekToken().text !== ']') { 15203 do { 15204 if (this.peek(']')) { 15205 // Support trailing commas per ES5.1. 15206 break; 15207 } 15208 elements.push(this.expression()); 15209 } while (this.expect(',')); 15210 } 15211 this.consume(']'); 15212 15213 return { type: AST.ArrayExpression, elements: elements }; 15214 }, 15215 15216 object: function() { 15217 var properties = [], property; 15218 if (this.peekToken().text !== '}') { 15219 do { 15220 if (this.peek('}')) { 15221 // Support trailing commas per ES5.1. 15222 break; 15223 } 15224 property = {type: AST.Property, kind: 'init'}; 15225 if (this.peek().constant) { 15226 property.key = this.constant(); 15227 property.computed = false; 15228 this.consume(':'); 15229 property.value = this.expression(); 15230 } else if (this.peek().identifier) { 15231 property.key = this.identifier(); 15232 property.computed = false; 15233 if (this.peek(':')) { 15234 this.consume(':'); 15235 property.value = this.expression(); 15236 } else { 15237 property.value = property.key; 15238 } 15239 } else if (this.peek('[')) { 15240 this.consume('['); 15241 property.key = this.expression(); 15242 this.consume(']'); 15243 property.computed = true; 15244 this.consume(':'); 15245 property.value = this.expression(); 15246 } else { 15247 this.throwError('invalid key', this.peek()); 15248 } 15249 properties.push(property); 15250 } while (this.expect(',')); 15251 } 15252 this.consume('}'); 15253 15254 return {type: AST.ObjectExpression, properties: properties }; 15255 }, 15256 15257 throwError: function(msg, token) { 15258 throw $parseMinErr('syntax', 15259 'Syntax Error: Token \'{0}\' {1} at column {2} of the expression [{3}] starting at [{4}].', 15260 token.text, msg, (token.index + 1), this.text, this.text.substring(token.index)); 15261 }, 15262 15263 consume: function(e1) { 15264 if (this.tokens.length === 0) { 15265 throw $parseMinErr('ueoe', 'Unexpected end of expression: {0}', this.text); 15266 } 15267 15268 var token = this.expect(e1); 15269 if (!token) { 15270 this.throwError('is unexpected, expecting [' + e1 + ']', this.peek()); 15271 } 15272 return token; 15273 }, 15274 15275 peekToken: function() { 15276 if (this.tokens.length === 0) { 15277 throw $parseMinErr('ueoe', 'Unexpected end of expression: {0}', this.text); 15278 } 15279 return this.tokens[0]; 15280 }, 15281 15282 peek: function(e1, e2, e3, e4) { 15283 return this.peekAhead(0, e1, e2, e3, e4); 15284 }, 15285 15286 peekAhead: function(i, e1, e2, e3, e4) { 15287 if (this.tokens.length > i) { 15288 var token = this.tokens[i]; 15289 var t = token.text; 15290 if (t === e1 || t === e2 || t === e3 || t === e4 || 15291 (!e1 && !e2 && !e3 && !e4)) { 15292 return token; 15293 } 15294 } 15295 return false; 15296 }, 15297 15298 expect: function(e1, e2, e3, e4) { 15299 var token = this.peek(e1, e2, e3, e4); 15300 if (token) { 15301 this.tokens.shift(); 15302 return token; 15303 } 15304 return false; 15305 }, 15306 15307 selfReferential: { 15308 'this': {type: AST.ThisExpression }, 15309 '$locals': {type: AST.LocalsExpression } 15310 } 15311}; 15312 15313function ifDefined(v, d) { 15314 return typeof v !== 'undefined' ? v : d; 15315} 15316 15317function plusFn(l, r) { 15318 if (typeof l === 'undefined') return r; 15319 if (typeof r === 'undefined') return l; 15320 return l + r; 15321} 15322 15323function isStateless($filter, filterName) { 15324 var fn = $filter(filterName); 15325 return !fn.$stateful; 15326} 15327 15328var PURITY_ABSOLUTE = 1; 15329var PURITY_RELATIVE = 2; 15330 15331// Detect nodes which could depend on non-shallow state of objects 15332function isPure(node, parentIsPure) { 15333 switch (node.type) { 15334 // Computed members might invoke a stateful toString() 15335 case AST.MemberExpression: 15336 if (node.computed) { 15337 return false; 15338 } 15339 break; 15340 15341 // Unary always convert to primative 15342 case AST.UnaryExpression: 15343 return PURITY_ABSOLUTE; 15344 15345 // The binary + operator can invoke a stateful toString(). 15346 case AST.BinaryExpression: 15347 return node.operator !== '+' ? PURITY_ABSOLUTE : false; 15348 15349 // Functions / filters probably read state from within objects 15350 case AST.CallExpression: 15351 return false; 15352 } 15353 15354 return (undefined === parentIsPure) ? PURITY_RELATIVE : parentIsPure; 15355} 15356 15357function findConstantAndWatchExpressions(ast, $filter, parentIsPure) { 15358 var allConstants; 15359 var argsToWatch; 15360 var isStatelessFilter; 15361 15362 var astIsPure = ast.isPure = isPure(ast, parentIsPure); 15363 15364 switch (ast.type) { 15365 case AST.Program: 15366 allConstants = true; 15367 forEach(ast.body, function(expr) { 15368 findConstantAndWatchExpressions(expr.expression, $filter, astIsPure); 15369 allConstants = allConstants && expr.expression.constant; 15370 }); 15371 ast.constant = allConstants; 15372 break; 15373 case AST.Literal: 15374 ast.constant = true; 15375 ast.toWatch = []; 15376 break; 15377 case AST.UnaryExpression: 15378 findConstantAndWatchExpressions(ast.argument, $filter, astIsPure); 15379 ast.constant = ast.argument.constant; 15380 ast.toWatch = ast.argument.toWatch; 15381 break; 15382 case AST.BinaryExpression: 15383 findConstantAndWatchExpressions(ast.left, $filter, astIsPure); 15384 findConstantAndWatchExpressions(ast.right, $filter, astIsPure); 15385 ast.constant = ast.left.constant && ast.right.constant; 15386 ast.toWatch = ast.left.toWatch.concat(ast.right.toWatch); 15387 break; 15388 case AST.LogicalExpression: 15389 findConstantAndWatchExpressions(ast.left, $filter, astIsPure); 15390 findConstantAndWatchExpressions(ast.right, $filter, astIsPure); 15391 ast.constant = ast.left.constant && ast.right.constant; 15392 ast.toWatch = ast.constant ? [] : [ast]; 15393 break; 15394 case AST.ConditionalExpression: 15395 findConstantAndWatchExpressions(ast.test, $filter, astIsPure); 15396 findConstantAndWatchExpressions(ast.alternate, $filter, astIsPure); 15397 findConstantAndWatchExpressions(ast.consequent, $filter, astIsPure); 15398 ast.constant = ast.test.constant && ast.alternate.constant && ast.consequent.constant; 15399 ast.toWatch = ast.constant ? [] : [ast]; 15400 break; 15401 case AST.Identifier: 15402 ast.constant = false; 15403 ast.toWatch = [ast]; 15404 break; 15405 case AST.MemberExpression: 15406 findConstantAndWatchExpressions(ast.object, $filter, astIsPure); 15407 if (ast.computed) { 15408 findConstantAndWatchExpressions(ast.property, $filter, astIsPure); 15409 } 15410 ast.constant = ast.object.constant && (!ast.computed || ast.property.constant); 15411 ast.toWatch = ast.constant ? [] : [ast]; 15412 break; 15413 case AST.CallExpression: 15414 isStatelessFilter = ast.filter ? isStateless($filter, ast.callee.name) : false; 15415 allConstants = isStatelessFilter; 15416 argsToWatch = []; 15417 forEach(ast.arguments, function(expr) { 15418 findConstantAndWatchExpressions(expr, $filter, astIsPure); 15419 allConstants = allConstants && expr.constant; 15420 argsToWatch.push.apply(argsToWatch, expr.toWatch); 15421 }); 15422 ast.constant = allConstants; 15423 ast.toWatch = isStatelessFilter ? argsToWatch : [ast]; 15424 break; 15425 case AST.AssignmentExpression: 15426 findConstantAndWatchExpressions(ast.left, $filter, astIsPure); 15427 findConstantAndWatchExpressions(ast.right, $filter, astIsPure); 15428 ast.constant = ast.left.constant && ast.right.constant; 15429 ast.toWatch = [ast]; 15430 break; 15431 case AST.ArrayExpression: 15432 allConstants = true; 15433 argsToWatch = []; 15434 forEach(ast.elements, function(expr) { 15435 findConstantAndWatchExpressions(expr, $filter, astIsPure); 15436 allConstants = allConstants && expr.constant; 15437 argsToWatch.push.apply(argsToWatch, expr.toWatch); 15438 }); 15439 ast.constant = allConstants; 15440 ast.toWatch = argsToWatch; 15441 break; 15442 case AST.ObjectExpression: 15443 allConstants = true; 15444 argsToWatch = []; 15445 forEach(ast.properties, function(property) { 15446 findConstantAndWatchExpressions(property.value, $filter, astIsPure); 15447 allConstants = allConstants && property.value.constant; 15448 argsToWatch.push.apply(argsToWatch, property.value.toWatch); 15449 if (property.computed) { 15450 //`{[key]: value}` implicitly does `key.toString()` which may be non-pure 15451 findConstantAndWatchExpressions(property.key, $filter, /*parentIsPure=*/false); 15452 allConstants = allConstants && property.key.constant; 15453 argsToWatch.push.apply(argsToWatch, property.key.toWatch); 15454 } 15455 }); 15456 ast.constant = allConstants; 15457 ast.toWatch = argsToWatch; 15458 break; 15459 case AST.ThisExpression: 15460 ast.constant = false; 15461 ast.toWatch = []; 15462 break; 15463 case AST.LocalsExpression: 15464 ast.constant = false; 15465 ast.toWatch = []; 15466 break; 15467 } 15468} 15469 15470function getInputs(body) { 15471 if (body.length !== 1) return; 15472 var lastExpression = body[0].expression; 15473 var candidate = lastExpression.toWatch; 15474 if (candidate.length !== 1) return candidate; 15475 return candidate[0] !== lastExpression ? candidate : undefined; 15476} 15477 15478function isAssignable(ast) { 15479 return ast.type === AST.Identifier || ast.type === AST.MemberExpression; 15480} 15481 15482function assignableAST(ast) { 15483 if (ast.body.length === 1 && isAssignable(ast.body[0].expression)) { 15484 return {type: AST.AssignmentExpression, left: ast.body[0].expression, right: {type: AST.NGValueParameter}, operator: '='}; 15485 } 15486} 15487 15488function isLiteral(ast) { 15489 return ast.body.length === 0 || 15490 ast.body.length === 1 && ( 15491 ast.body[0].expression.type === AST.Literal || 15492 ast.body[0].expression.type === AST.ArrayExpression || 15493 ast.body[0].expression.type === AST.ObjectExpression); 15494} 15495 15496function isConstant(ast) { 15497 return ast.constant; 15498} 15499 15500function ASTCompiler($filter) { 15501 this.$filter = $filter; 15502} 15503 15504ASTCompiler.prototype = { 15505 compile: function(ast) { 15506 var self = this; 15507 this.state = { 15508 nextId: 0, 15509 filters: {}, 15510 fn: {vars: [], body: [], own: {}}, 15511 assign: {vars: [], body: [], own: {}}, 15512 inputs: [] 15513 }; 15514 findConstantAndWatchExpressions(ast, self.$filter); 15515 var extra = ''; 15516 var assignable; 15517 this.stage = 'assign'; 15518 if ((assignable = assignableAST(ast))) { 15519 this.state.computing = 'assign'; 15520 var result = this.nextId(); 15521 this.recurse(assignable, result); 15522 this.return_(result); 15523 extra = 'fn.assign=' + this.generateFunction('assign', 's,v,l'); 15524 } 15525 var toWatch = getInputs(ast.body); 15526 self.stage = 'inputs'; 15527 forEach(toWatch, function(watch, key) { 15528 var fnKey = 'fn' + key; 15529 self.state[fnKey] = {vars: [], body: [], own: {}}; 15530 self.state.computing = fnKey; 15531 var intoId = self.nextId(); 15532 self.recurse(watch, intoId); 15533 self.return_(intoId); 15534 self.state.inputs.push({name: fnKey, isPure: watch.isPure}); 15535 watch.watchId = key; 15536 }); 15537 this.state.computing = 'fn'; 15538 this.stage = 'main'; 15539 this.recurse(ast); 15540 var fnString = 15541 // The build and minification steps remove the string "use strict" from the code, but this is done using a regex. 15542 // This is a workaround for this until we do a better job at only removing the prefix only when we should. 15543 '"' + this.USE + ' ' + this.STRICT + '";\n' + 15544 this.filterPrefix() + 15545 'var fn=' + this.generateFunction('fn', 's,l,a,i') + 15546 extra + 15547 this.watchFns() + 15548 'return fn;'; 15549 15550 // eslint-disable-next-line no-new-func 15551 var fn = (new Function('$filter', 15552 'getStringValue', 15553 'ifDefined', 15554 'plus', 15555 fnString))( 15556 this.$filter, 15557 getStringValue, 15558 ifDefined, 15559 plusFn); 15560 this.state = this.stage = undefined; 15561 return fn; 15562 }, 15563 15564 USE: 'use', 15565 15566 STRICT: 'strict', 15567 15568 watchFns: function() { 15569 var result = []; 15570 var inputs = this.state.inputs; 15571 var self = this; 15572 forEach(inputs, function(input) { 15573 result.push('var ' + input.name + '=' + self.generateFunction(input.name, 's')); 15574 if (input.isPure) { 15575 result.push(input.name, '.isPure=' + JSON.stringify(input.isPure) + ';'); 15576 } 15577 }); 15578 if (inputs.length) { 15579 result.push('fn.inputs=[' + inputs.map(function(i) { return i.name; }).join(',') + '];'); 15580 } 15581 return result.join(''); 15582 }, 15583 15584 generateFunction: function(name, params) { 15585 return 'function(' + params + '){' + 15586 this.varsPrefix(name) + 15587 this.body(name) + 15588 '};'; 15589 }, 15590 15591 filterPrefix: function() { 15592 var parts = []; 15593 var self = this; 15594 forEach(this.state.filters, function(id, filter) { 15595 parts.push(id + '=$filter(' + self.escape(filter) + ')'); 15596 }); 15597 if (parts.length) return 'var ' + parts.join(',') + ';'; 15598 return ''; 15599 }, 15600 15601 varsPrefix: function(section) { 15602 return this.state[section].vars.length ? 'var ' + this.state[section].vars.join(',') + ';' : ''; 15603 }, 15604 15605 body: function(section) { 15606 return this.state[section].body.join(''); 15607 }, 15608 15609 recurse: function(ast, intoId, nameId, recursionFn, create, skipWatchIdCheck) { 15610 var left, right, self = this, args, expression, computed; 15611 recursionFn = recursionFn || noop; 15612 if (!skipWatchIdCheck && isDefined(ast.watchId)) { 15613 intoId = intoId || this.nextId(); 15614 this.if_('i', 15615 this.lazyAssign(intoId, this.computedMember('i', ast.watchId)), 15616 this.lazyRecurse(ast, intoId, nameId, recursionFn, create, true) 15617 ); 15618 return; 15619 } 15620 switch (ast.type) { 15621 case AST.Program: 15622 forEach(ast.body, function(expression, pos) { 15623 self.recurse(expression.expression, undefined, undefined, function(expr) { right = expr; }); 15624 if (pos !== ast.body.length - 1) { 15625 self.current().body.push(right, ';'); 15626 } else { 15627 self.return_(right); 15628 } 15629 }); 15630 break; 15631 case AST.Literal: 15632 expression = this.escape(ast.value); 15633 this.assign(intoId, expression); 15634 recursionFn(intoId || expression); 15635 break; 15636 case AST.UnaryExpression: 15637 this.recurse(ast.argument, undefined, undefined, function(expr) { right = expr; }); 15638 expression = ast.operator + '(' + this.ifDefined(right, 0) + ')'; 15639 this.assign(intoId, expression); 15640 recursionFn(expression); 15641 break; 15642 case AST.BinaryExpression: 15643 this.recurse(ast.left, undefined, undefined, function(expr) { left = expr; }); 15644 this.recurse(ast.right, undefined, undefined, function(expr) { right = expr; }); 15645 if (ast.operator === '+') { 15646 expression = this.plus(left, right); 15647 } else if (ast.operator === '-') { 15648 expression = this.ifDefined(left, 0) + ast.operator + this.ifDefined(right, 0); 15649 } else { 15650 expression = '(' + left + ')' + ast.operator + '(' + right + ')'; 15651 } 15652 this.assign(intoId, expression); 15653 recursionFn(expression); 15654 break; 15655 case AST.LogicalExpression: 15656 intoId = intoId || this.nextId(); 15657 self.recurse(ast.left, intoId); 15658 self.if_(ast.operator === '&&' ? intoId : self.not(intoId), self.lazyRecurse(ast.right, intoId)); 15659 recursionFn(intoId); 15660 break; 15661 case AST.ConditionalExpression: 15662 intoId = intoId || this.nextId(); 15663 self.recurse(ast.test, intoId); 15664 self.if_(intoId, self.lazyRecurse(ast.alternate, intoId), self.lazyRecurse(ast.consequent, intoId)); 15665 recursionFn(intoId); 15666 break; 15667 case AST.Identifier: 15668 intoId = intoId || this.nextId(); 15669 if (nameId) { 15670 nameId.context = self.stage === 'inputs' ? 's' : this.assign(this.nextId(), this.getHasOwnProperty('l', ast.name) + '?l:s'); 15671 nameId.computed = false; 15672 nameId.name = ast.name; 15673 } 15674 self.if_(self.stage === 'inputs' || self.not(self.getHasOwnProperty('l', ast.name)), 15675 function() { 15676 self.if_(self.stage === 'inputs' || 's', function() { 15677 if (create && create !== 1) { 15678 self.if_( 15679 self.isNull(self.nonComputedMember('s', ast.name)), 15680 self.lazyAssign(self.nonComputedMember('s', ast.name), '{}')); 15681 } 15682 self.assign(intoId, self.nonComputedMember('s', ast.name)); 15683 }); 15684 }, intoId && self.lazyAssign(intoId, self.nonComputedMember('l', ast.name)) 15685 ); 15686 recursionFn(intoId); 15687 break; 15688 case AST.MemberExpression: 15689 left = nameId && (nameId.context = this.nextId()) || this.nextId(); 15690 intoId = intoId || this.nextId(); 15691 self.recurse(ast.object, left, undefined, function() { 15692 self.if_(self.notNull(left), function() { 15693 if (ast.computed) { 15694 right = self.nextId(); 15695 self.recurse(ast.property, right); 15696 self.getStringValue(right); 15697 if (create && create !== 1) { 15698 self.if_(self.not(self.computedMember(left, right)), self.lazyAssign(self.computedMember(left, right), '{}')); 15699 } 15700 expression = self.computedMember(left, right); 15701 self.assign(intoId, expression); 15702 if (nameId) { 15703 nameId.computed = true; 15704 nameId.name = right; 15705 } 15706 } else { 15707 if (create && create !== 1) { 15708 self.if_(self.isNull(self.nonComputedMember(left, ast.property.name)), self.lazyAssign(self.nonComputedMember(left, ast.property.name), '{}')); 15709 } 15710 expression = self.nonComputedMember(left, ast.property.name); 15711 self.assign(intoId, expression); 15712 if (nameId) { 15713 nameId.computed = false; 15714 nameId.name = ast.property.name; 15715 } 15716 } 15717 }, function() { 15718 self.assign(intoId, 'undefined'); 15719 }); 15720 recursionFn(intoId); 15721 }, !!create); 15722 break; 15723 case AST.CallExpression: 15724 intoId = intoId || this.nextId(); 15725 if (ast.filter) { 15726 right = self.filter(ast.callee.name); 15727 args = []; 15728 forEach(ast.arguments, function(expr) { 15729 var argument = self.nextId(); 15730 self.recurse(expr, argument); 15731 args.push(argument); 15732 }); 15733 expression = right + '(' + args.join(',') + ')'; 15734 self.assign(intoId, expression); 15735 recursionFn(intoId); 15736 } else { 15737 right = self.nextId(); 15738 left = {}; 15739 args = []; 15740 self.recurse(ast.callee, right, left, function() { 15741 self.if_(self.notNull(right), function() { 15742 forEach(ast.arguments, function(expr) { 15743 self.recurse(expr, ast.constant ? undefined : self.nextId(), undefined, function(argument) { 15744 args.push(argument); 15745 }); 15746 }); 15747 if (left.name) { 15748 expression = self.member(left.context, left.name, left.computed) + '(' + args.join(',') + ')'; 15749 } else { 15750 expression = right + '(' + args.join(',') + ')'; 15751 } 15752 self.assign(intoId, expression); 15753 }, function() { 15754 self.assign(intoId, 'undefined'); 15755 }); 15756 recursionFn(intoId); 15757 }); 15758 } 15759 break; 15760 case AST.AssignmentExpression: 15761 right = this.nextId(); 15762 left = {}; 15763 this.recurse(ast.left, undefined, left, function() { 15764 self.if_(self.notNull(left.context), function() { 15765 self.recurse(ast.right, right); 15766 expression = self.member(left.context, left.name, left.computed) + ast.operator + right; 15767 self.assign(intoId, expression); 15768 recursionFn(intoId || expression); 15769 }); 15770 }, 1); 15771 break; 15772 case AST.ArrayExpression: 15773 args = []; 15774 forEach(ast.elements, function(expr) { 15775 self.recurse(expr, ast.constant ? undefined : self.nextId(), undefined, function(argument) { 15776 args.push(argument); 15777 }); 15778 }); 15779 expression = '[' + args.join(',') + ']'; 15780 this.assign(intoId, expression); 15781 recursionFn(intoId || expression); 15782 break; 15783 case AST.ObjectExpression: 15784 args = []; 15785 computed = false; 15786 forEach(ast.properties, function(property) { 15787 if (property.computed) { 15788 computed = true; 15789 } 15790 }); 15791 if (computed) { 15792 intoId = intoId || this.nextId(); 15793 this.assign(intoId, '{}'); 15794 forEach(ast.properties, function(property) { 15795 if (property.computed) { 15796 left = self.nextId(); 15797 self.recurse(property.key, left); 15798 } else { 15799 left = property.key.type === AST.Identifier ? 15800 property.key.name : 15801 ('' + property.key.value); 15802 } 15803 right = self.nextId(); 15804 self.recurse(property.value, right); 15805 self.assign(self.member(intoId, left, property.computed), right); 15806 }); 15807 } else { 15808 forEach(ast.properties, function(property) { 15809 self.recurse(property.value, ast.constant ? undefined : self.nextId(), undefined, function(expr) { 15810 args.push(self.escape( 15811 property.key.type === AST.Identifier ? property.key.name : 15812 ('' + property.key.value)) + 15813 ':' + expr); 15814 }); 15815 }); 15816 expression = '{' + args.join(',') + '}'; 15817 this.assign(intoId, expression); 15818 } 15819 recursionFn(intoId || expression); 15820 break; 15821 case AST.ThisExpression: 15822 this.assign(intoId, 's'); 15823 recursionFn(intoId || 's'); 15824 break; 15825 case AST.LocalsExpression: 15826 this.assign(intoId, 'l'); 15827 recursionFn(intoId || 'l'); 15828 break; 15829 case AST.NGValueParameter: 15830 this.assign(intoId, 'v'); 15831 recursionFn(intoId || 'v'); 15832 break; 15833 } 15834 }, 15835 15836 getHasOwnProperty: function(element, property) { 15837 var key = element + '.' + property; 15838 var own = this.current().own; 15839 if (!own.hasOwnProperty(key)) { 15840 own[key] = this.nextId(false, element + '&&(' + this.escape(property) + ' in ' + element + ')'); 15841 } 15842 return own[key]; 15843 }, 15844 15845 assign: function(id, value) { 15846 if (!id) return; 15847 this.current().body.push(id, '=', value, ';'); 15848 return id; 15849 }, 15850 15851 filter: function(filterName) { 15852 if (!this.state.filters.hasOwnProperty(filterName)) { 15853 this.state.filters[filterName] = this.nextId(true); 15854 } 15855 return this.state.filters[filterName]; 15856 }, 15857 15858 ifDefined: function(id, defaultValue) { 15859 return 'ifDefined(' + id + ',' + this.escape(defaultValue) + ')'; 15860 }, 15861 15862 plus: function(left, right) { 15863 return 'plus(' + left + ',' + right + ')'; 15864 }, 15865 15866 return_: function(id) { 15867 this.current().body.push('return ', id, ';'); 15868 }, 15869 15870 if_: function(test, alternate, consequent) { 15871 if (test === true) { 15872 alternate(); 15873 } else { 15874 var body = this.current().body; 15875 body.push('if(', test, '){'); 15876 alternate(); 15877 body.push('}'); 15878 if (consequent) { 15879 body.push('else{'); 15880 consequent(); 15881 body.push('}'); 15882 } 15883 } 15884 }, 15885 15886 not: function(expression) { 15887 return '!(' + expression + ')'; 15888 }, 15889 15890 isNull: function(expression) { 15891 return expression + '==null'; 15892 }, 15893 15894 notNull: function(expression) { 15895 return expression + '!=null'; 15896 }, 15897 15898 nonComputedMember: function(left, right) { 15899 var SAFE_IDENTIFIER = /^[$_a-zA-Z][$_a-zA-Z0-9]*$/; 15900 var UNSAFE_CHARACTERS = /[^$_a-zA-Z0-9]/g; 15901 if (SAFE_IDENTIFIER.test(right)) { 15902 return left + '.' + right; 15903 } else { 15904 return left + '["' + right.replace(UNSAFE_CHARACTERS, this.stringEscapeFn) + '"]'; 15905 } 15906 }, 15907 15908 computedMember: function(left, right) { 15909 return left + '[' + right + ']'; 15910 }, 15911 15912 member: function(left, right, computed) { 15913 if (computed) return this.computedMember(left, right); 15914 return this.nonComputedMember(left, right); 15915 }, 15916 15917 getStringValue: function(item) { 15918 this.assign(item, 'getStringValue(' + item + ')'); 15919 }, 15920 15921 lazyRecurse: function(ast, intoId, nameId, recursionFn, create, skipWatchIdCheck) { 15922 var self = this; 15923 return function() { 15924 self.recurse(ast, intoId, nameId, recursionFn, create, skipWatchIdCheck); 15925 }; 15926 }, 15927 15928 lazyAssign: function(id, value) { 15929 var self = this; 15930 return function() { 15931 self.assign(id, value); 15932 }; 15933 }, 15934 15935 stringEscapeRegex: /[^ a-zA-Z0-9]/g, 15936 15937 stringEscapeFn: function(c) { 15938 return '\\u' + ('0000' + c.charCodeAt(0).toString(16)).slice(-4); 15939 }, 15940 15941 escape: function(value) { 15942 if (isString(value)) return '\'' + value.replace(this.stringEscapeRegex, this.stringEscapeFn) + '\''; 15943 if (isNumber(value)) return value.toString(); 15944 if (value === true) return 'true'; 15945 if (value === false) return 'false'; 15946 if (value === null) return 'null'; 15947 if (typeof value === 'undefined') return 'undefined'; 15948 15949 throw $parseMinErr('esc', 'IMPOSSIBLE'); 15950 }, 15951 15952 nextId: function(skip, init) { 15953 var id = 'v' + (this.state.nextId++); 15954 if (!skip) { 15955 this.current().vars.push(id + (init ? '=' + init : '')); 15956 } 15957 return id; 15958 }, 15959 15960 current: function() { 15961 return this.state[this.state.computing]; 15962 } 15963}; 15964 15965 15966function ASTInterpreter($filter) { 15967 this.$filter = $filter; 15968} 15969 15970ASTInterpreter.prototype = { 15971 compile: function(ast) { 15972 var self = this; 15973 findConstantAndWatchExpressions(ast, self.$filter); 15974 var assignable; 15975 var assign; 15976 if ((assignable = assignableAST(ast))) { 15977 assign = this.recurse(assignable); 15978 } 15979 var toWatch = getInputs(ast.body); 15980 var inputs; 15981 if (toWatch) { 15982 inputs = []; 15983 forEach(toWatch, function(watch, key) { 15984 var input = self.recurse(watch); 15985 input.isPure = watch.isPure; 15986 watch.input = input; 15987 inputs.push(input); 15988 watch.watchId = key; 15989 }); 15990 } 15991 var expressions = []; 15992 forEach(ast.body, function(expression) { 15993 expressions.push(self.recurse(expression.expression)); 15994 }); 15995 var fn = ast.body.length === 0 ? noop : 15996 ast.body.length === 1 ? expressions[0] : 15997 function(scope, locals) { 15998 var lastValue; 15999 forEach(expressions, function(exp) { 16000 lastValue = exp(scope, locals); 16001 }); 16002 return lastValue; 16003 }; 16004 if (assign) { 16005 fn.assign = function(scope, value, locals) { 16006 return assign(scope, locals, value); 16007 }; 16008 } 16009 if (inputs) { 16010 fn.inputs = inputs; 16011 } 16012 return fn; 16013 }, 16014 16015 recurse: function(ast, context, create) { 16016 var left, right, self = this, args; 16017 if (ast.input) { 16018 return this.inputs(ast.input, ast.watchId); 16019 } 16020 switch (ast.type) { 16021 case AST.Literal: 16022 return this.value(ast.value, context); 16023 case AST.UnaryExpression: 16024 right = this.recurse(ast.argument); 16025 return this['unary' + ast.operator](right, context); 16026 case AST.BinaryExpression: 16027 left = this.recurse(ast.left); 16028 right = this.recurse(ast.right); 16029 return this['binary' + ast.operator](left, right, context); 16030 case AST.LogicalExpression: 16031 left = this.recurse(ast.left); 16032 right = this.recurse(ast.right); 16033 return this['binary' + ast.operator](left, right, context); 16034 case AST.ConditionalExpression: 16035 return this['ternary?:']( 16036 this.recurse(ast.test), 16037 this.recurse(ast.alternate), 16038 this.recurse(ast.consequent), 16039 context 16040 ); 16041 case AST.Identifier: 16042 return self.identifier(ast.name, context, create); 16043 case AST.MemberExpression: 16044 left = this.recurse(ast.object, false, !!create); 16045 if (!ast.computed) { 16046 right = ast.property.name; 16047 } 16048 if (ast.computed) right = this.recurse(ast.property); 16049 return ast.computed ? 16050 this.computedMember(left, right, context, create) : 16051 this.nonComputedMember(left, right, context, create); 16052 case AST.CallExpression: 16053 args = []; 16054 forEach(ast.arguments, function(expr) { 16055 args.push(self.recurse(expr)); 16056 }); 16057 if (ast.filter) right = this.$filter(ast.callee.name); 16058 if (!ast.filter) right = this.recurse(ast.callee, true); 16059 return ast.filter ? 16060 function(scope, locals, assign, inputs) { 16061 var values = []; 16062 for (var i = 0; i < args.length; ++i) { 16063 values.push(args[i](scope, locals, assign, inputs)); 16064 } 16065 var value = right.apply(undefined, values, inputs); 16066 return context ? {context: undefined, name: undefined, value: value} : value; 16067 } : 16068 function(scope, locals, assign, inputs) { 16069 var rhs = right(scope, locals, assign, inputs); 16070 var value; 16071 if (rhs.value != null) { 16072 var values = []; 16073 for (var i = 0; i < args.length; ++i) { 16074 values.push(args[i](scope, locals, assign, inputs)); 16075 } 16076 value = rhs.value.apply(rhs.context, values); 16077 } 16078 return context ? {value: value} : value; 16079 }; 16080 case AST.AssignmentExpression: 16081 left = this.recurse(ast.left, true, 1); 16082 right = this.recurse(ast.right); 16083 return function(scope, locals, assign, inputs) { 16084 var lhs = left(scope, locals, assign, inputs); 16085 var rhs = right(scope, locals, assign, inputs); 16086 lhs.context[lhs.name] = rhs; 16087 return context ? {value: rhs} : rhs; 16088 }; 16089 case AST.ArrayExpression: 16090 args = []; 16091 forEach(ast.elements, function(expr) { 16092 args.push(self.recurse(expr)); 16093 }); 16094 return function(scope, locals, assign, inputs) { 16095 var value = []; 16096 for (var i = 0; i < args.length; ++i) { 16097 value.push(args[i](scope, locals, assign, inputs)); 16098 } 16099 return context ? {value: value} : value; 16100 }; 16101 case AST.ObjectExpression: 16102 args = []; 16103 forEach(ast.properties, function(property) { 16104 if (property.computed) { 16105 args.push({key: self.recurse(property.key), 16106 computed: true, 16107 value: self.recurse(property.value) 16108 }); 16109 } else { 16110 args.push({key: property.key.type === AST.Identifier ? 16111 property.key.name : 16112 ('' + property.key.value), 16113 computed: false, 16114 value: self.recurse(property.value) 16115 }); 16116 } 16117 }); 16118 return function(scope, locals, assign, inputs) { 16119 var value = {}; 16120 for (var i = 0; i < args.length; ++i) { 16121 if (args[i].computed) { 16122 value[args[i].key(scope, locals, assign, inputs)] = args[i].value(scope, locals, assign, inputs); 16123 } else { 16124 value[args[i].key] = args[i].value(scope, locals, assign, inputs); 16125 } 16126 } 16127 return context ? {value: value} : value; 16128 }; 16129 case AST.ThisExpression: 16130 return function(scope) { 16131 return context ? {value: scope} : scope; 16132 }; 16133 case AST.LocalsExpression: 16134 return function(scope, locals) { 16135 return context ? {value: locals} : locals; 16136 }; 16137 case AST.NGValueParameter: 16138 return function(scope, locals, assign) { 16139 return context ? {value: assign} : assign; 16140 }; 16141 } 16142 }, 16143 16144 'unary+': function(argument, context) { 16145 return function(scope, locals, assign, inputs) { 16146 var arg = argument(scope, locals, assign, inputs); 16147 if (isDefined(arg)) { 16148 arg = +arg; 16149 } else { 16150 arg = 0; 16151 } 16152 return context ? {value: arg} : arg; 16153 }; 16154 }, 16155 'unary-': function(argument, context) { 16156 return function(scope, locals, assign, inputs) { 16157 var arg = argument(scope, locals, assign, inputs); 16158 if (isDefined(arg)) { 16159 arg = -arg; 16160 } else { 16161 arg = -0; 16162 } 16163 return context ? {value: arg} : arg; 16164 }; 16165 }, 16166 'unary!': function(argument, context) { 16167 return function(scope, locals, assign, inputs) { 16168 var arg = !argument(scope, locals, assign, inputs); 16169 return context ? {value: arg} : arg; 16170 }; 16171 }, 16172 'binary+': function(left, right, context) { 16173 return function(scope, locals, assign, inputs) { 16174 var lhs = left(scope, locals, assign, inputs); 16175 var rhs = right(scope, locals, assign, inputs); 16176 var arg = plusFn(lhs, rhs); 16177 return context ? {value: arg} : arg; 16178 }; 16179 }, 16180 'binary-': function(left, right, context) { 16181 return function(scope, locals, assign, inputs) { 16182 var lhs = left(scope, locals, assign, inputs); 16183 var rhs = right(scope, locals, assign, inputs); 16184 var arg = (isDefined(lhs) ? lhs : 0) - (isDefined(rhs) ? rhs : 0); 16185 return context ? {value: arg} : arg; 16186 }; 16187 }, 16188 'binary*': function(left, right, context) { 16189 return function(scope, locals, assign, inputs) { 16190 var arg = left(scope, locals, assign, inputs) * right(scope, locals, assign, inputs); 16191 return context ? {value: arg} : arg; 16192 }; 16193 }, 16194 'binary/': function(left, right, context) { 16195 return function(scope, locals, assign, inputs) { 16196 var arg = left(scope, locals, assign, inputs) / right(scope, locals, assign, inputs); 16197 return context ? {value: arg} : arg; 16198 }; 16199 }, 16200 'binary%': function(left, right, context) { 16201 return function(scope, locals, assign, inputs) { 16202 var arg = left(scope, locals, assign, inputs) % right(scope, locals, assign, inputs); 16203 return context ? {value: arg} : arg; 16204 }; 16205 }, 16206 'binary===': function(left, right, context) { 16207 return function(scope, locals, assign, inputs) { 16208 var arg = left(scope, locals, assign, inputs) === right(scope, locals, assign, inputs); 16209 return context ? {value: arg} : arg; 16210 }; 16211 }, 16212 'binary!==': function(left, right, context) { 16213 return function(scope, locals, assign, inputs) { 16214 var arg = left(scope, locals, assign, inputs) !== right(scope, locals, assign, inputs); 16215 return context ? {value: arg} : arg; 16216 }; 16217 }, 16218 'binary==': function(left, right, context) { 16219 return function(scope, locals, assign, inputs) { 16220 // eslint-disable-next-line eqeqeq 16221 var arg = left(scope, locals, assign, inputs) == right(scope, locals, assign, inputs); 16222 return context ? {value: arg} : arg; 16223 }; 16224 }, 16225 'binary!=': function(left, right, context) { 16226 return function(scope, locals, assign, inputs) { 16227 // eslint-disable-next-line eqeqeq 16228 var arg = left(scope, locals, assign, inputs) != right(scope, locals, assign, inputs); 16229 return context ? {value: arg} : arg; 16230 }; 16231 }, 16232 'binary<': function(left, right, context) { 16233 return function(scope, locals, assign, inputs) { 16234 var arg = left(scope, locals, assign, inputs) < right(scope, locals, assign, inputs); 16235 return context ? {value: arg} : arg; 16236 }; 16237 }, 16238 'binary>': function(left, right, context) { 16239 return function(scope, locals, assign, inputs) { 16240 var arg = left(scope, locals, assign, inputs) > right(scope, locals, assign, inputs); 16241 return context ? {value: arg} : arg; 16242 }; 16243 }, 16244 'binary<=': function(left, right, context) { 16245 return function(scope, locals, assign, inputs) { 16246 var arg = left(scope, locals, assign, inputs) <= right(scope, locals, assign, inputs); 16247 return context ? {value: arg} : arg; 16248 }; 16249 }, 16250 'binary>=': function(left, right, context) { 16251 return function(scope, locals, assign, inputs) { 16252 var arg = left(scope, locals, assign, inputs) >= right(scope, locals, assign, inputs); 16253 return context ? {value: arg} : arg; 16254 }; 16255 }, 16256 'binary&&': function(left, right, context) { 16257 return function(scope, locals, assign, inputs) { 16258 var arg = left(scope, locals, assign, inputs) && right(scope, locals, assign, inputs); 16259 return context ? {value: arg} : arg; 16260 }; 16261 }, 16262 'binary||': function(left, right, context) { 16263 return function(scope, locals, assign, inputs) { 16264 var arg = left(scope, locals, assign, inputs) || right(scope, locals, assign, inputs); 16265 return context ? {value: arg} : arg; 16266 }; 16267 }, 16268 'ternary?:': function(test, alternate, consequent, context) { 16269 return function(scope, locals, assign, inputs) { 16270 var arg = test(scope, locals, assign, inputs) ? alternate(scope, locals, assign, inputs) : consequent(scope, locals, assign, inputs); 16271 return context ? {value: arg} : arg; 16272 }; 16273 }, 16274 value: function(value, context) { 16275 return function() { return context ? {context: undefined, name: undefined, value: value} : value; }; 16276 }, 16277 identifier: function(name, context, create) { 16278 return function(scope, locals, assign, inputs) { 16279 var base = locals && (name in locals) ? locals : scope; 16280 if (create && create !== 1 && base && base[name] == null) { 16281 base[name] = {}; 16282 } 16283 var value = base ? base[name] : undefined; 16284 if (context) { 16285 return {context: base, name: name, value: value}; 16286 } else { 16287 return value; 16288 } 16289 }; 16290 }, 16291 computedMember: function(left, right, context, create) { 16292 return function(scope, locals, assign, inputs) { 16293 var lhs = left(scope, locals, assign, inputs); 16294 var rhs; 16295 var value; 16296 if (lhs != null) { 16297 rhs = right(scope, locals, assign, inputs); 16298 rhs = getStringValue(rhs); 16299 if (create && create !== 1) { 16300 if (lhs && !(lhs[rhs])) { 16301 lhs[rhs] = {}; 16302 } 16303 } 16304 value = lhs[rhs]; 16305 } 16306 if (context) { 16307 return {context: lhs, name: rhs, value: value}; 16308 } else { 16309 return value; 16310 } 16311 }; 16312 }, 16313 nonComputedMember: function(left, right, context, create) { 16314 return function(scope, locals, assign, inputs) { 16315 var lhs = left(scope, locals, assign, inputs); 16316 if (create && create !== 1) { 16317 if (lhs && lhs[right] == null) { 16318 lhs[right] = {}; 16319 } 16320 } 16321 var value = lhs != null ? lhs[right] : undefined; 16322 if (context) { 16323 return {context: lhs, name: right, value: value}; 16324 } else { 16325 return value; 16326 } 16327 }; 16328 }, 16329 inputs: function(input, watchId) { 16330 return function(scope, value, locals, inputs) { 16331 if (inputs) return inputs[watchId]; 16332 return input(scope, value, locals); 16333 }; 16334 } 16335}; 16336 16337/** 16338 * @constructor 16339 */ 16340function Parser(lexer, $filter, options) { 16341 this.ast = new AST(lexer, options); 16342 this.astCompiler = options.csp ? new ASTInterpreter($filter) : 16343 new ASTCompiler($filter); 16344} 16345 16346Parser.prototype = { 16347 constructor: Parser, 16348 16349 parse: function(text) { 16350 var ast = this.
vendor: 8,958 bytes, lines 16350-16588
16350ast.ast(text); 16351 var fn = this.astCompiler.compile(ast); 16352 fn.literal = isLiteral(ast); 16353 fn.constant = isConstant(ast); 16354 return fn; 16355 } 16356}; 16357 16358function getValueOf(value) { 16359 return isFunction(value.valueOf) ? value.valueOf() : objectValueOf.call(value); 16360} 16361 16362/////////////////////////////////// 16363 16364/** 16365 * @ngdoc service 16366 * @name $parse 16367 * @kind function 16368 * 16369 * @description 16370 * 16371 * Converts Angular {@link guide/expression expression} into a function. 16372 * 16373 * ```js 16374 * var getter = $parse('user.name'); 16375 * var setter = getter.assign; 16376 * var context = {user:{name:'angular'}}; 16377 * var locals = {user:{name:'local'}}; 16378 * 16379 * expect(getter(context)).toEqual('angular'); 16380 * setter(context, 'newValue'); 16381 * expect(context.user.name).toEqual('newValue'); 16382 * expect(getter(context, locals)).toEqual('local'); 16383 * ``` 16384 * 16385 * 16386 * @param {string} expression String expression to compile. 16387 * @returns {function(context, locals)} a function which represents the compiled expression: 16388 * 16389 * * `context` – `{object}` – an object against which any expressions embedded in the strings 16390 * are evaluated against (typically a scope object). 16391 * * `locals` – `{object=}` – local variables context object, useful for overriding values in 16392 * `context`. 16393 * 16394 * The returned function also has the following properties: 16395 * * `literal` – `{boolean}` – whether the expression's top-level node is a JavaScript 16396 * literal. 16397 * * `constant` – `{boolean}` – whether the expression is made entirely of JavaScript 16398 * constant literals. 16399 * * `assign` – `{?function(context, value)}` – if the expression is assignable, this will be 16400 * set to a function to change its value on the given context. 16401 * 16402 */ 16403 16404 16405/** 16406 * @ngdoc provider 16407 * @name $parseProvider 16408 * @this 16409 * 16410 * @description 16411 * `$parseProvider` can be used for configuring the default behavior of the {@link ng.$parse $parse} 16412 * service. 16413 */ 16414function $ParseProvider() { 16415 var cache = createMap(); 16416 var literals = { 16417 'true': true, 16418 'false': false, 16419 'null': null, 16420 'undefined': undefined 16421 }; 16422 var identStart, identContinue; 16423 16424 /** 16425 * @ngdoc method 16426 * @name $parseProvider#addLiteral 16427 * @description 16428 * 16429 * Configure $parse service to add literal values that will be present as literal at expressions. 16430 * 16431 * @param {string} literalName Token for the literal value. The literal name value must be a valid literal name. 16432 * @param {*} literalValue Value for this literal. All literal values must be primitives or `undefined`. 16433 * 16434 **/ 16435 this.addLiteral = function(literalName, literalValue) { 16436 literals[literalName] = literalValue; 16437 }; 16438 16439 /** 16440 * @ngdoc method 16441 * @name $parseProvider#setIdentifierFns 16442 * 16443 * @description 16444 * 16445 * Allows defining the set of characters that are allowed in Angular expressions. The function 16446 * `identifierStart` will get called to know if a given character is a valid character to be the 16447 * first character for an identifier. The function `identifierContinue` will get called to know if 16448 * a given character is a valid character to be a follow-up identifier character. The functions 16449 * `identifierStart` and `identifierContinue` will receive as arguments the single character to be 16450 * identifier and the character code point. These arguments will be `string` and `numeric`. Keep in 16451 * mind that the `string` parameter can be two characters long depending on the character 16452 * representation. It is expected for the function to return `true` or `false`, whether that 16453 * character is allowed or not. 16454 * 16455 * Since this function will be called extensively, keep the implementation of these functions fast, 16456 * as the performance of these functions have a direct impact on the expressions parsing speed. 16457 * 16458 * @param {function=} identifierStart The function that will decide whether the given character is 16459 * a valid identifier start character. 16460 * @param {function=} identifierContinue The function that will decide whether the given character is 16461 * a valid identifier continue character. 16462 */ 16463 this.setIdentifierFns = function(identifierStart, identifierContinue) { 16464 identStart = identifierStart; 16465 identContinue = identifierContinue; 16466 return this; 16467 }; 16468 16469 this.$get = ['$filter', function($filter) { 16470 var noUnsafeEval = csp().noUnsafeEval; 16471 var $parseOptions = { 16472 csp: noUnsafeEval, 16473 literals: copy(literals), 16474 isIdentifierStart: isFunction(identStart) && identStart, 16475 isIdentifierContinue: isFunction(identContinue) && identContinue 16476 }; 16477 return $parse; 16478 16479 function $parse(exp, interceptorFn) { 16480 var parsedExpression, oneTime, cacheKey; 16481 16482 switch (typeof exp) { 16483 case 'string': 16484 exp = exp.trim(); 16485 cacheKey = exp; 16486 16487 parsedExpression = cache[cacheKey]; 16488 16489 if (!parsedExpression) { 16490 if (exp.charAt(0) === ':' && exp.charAt(1) === ':') { 16491 oneTime = true; 16492 exp = exp.substring(2); 16493 } 16494 var lexer = new Lexer($parseOptions); 16495 var parser = new Parser(lexer, $filter, $parseOptions); 16496 parsedExpression = parser.parse(exp); 16497 if (parsedExpression.constant) { 16498 parsedExpression.$$watchDelegate = constantWatchDelegate; 16499 } else if (oneTime) { 16500 parsedExpression.$$watchDelegate = parsedExpression.literal ? 16501 oneTimeLiteralWatchDelegate : oneTimeWatchDelegate; 16502 } else if (parsedExpression.inputs) { 16503 parsedExpression.$$watchDelegate = inputsWatchDelegate; 16504 } 16505 cache[cacheKey] = parsedExpression; 16506 } 16507 return addInterceptor(parsedExpression, interceptorFn); 16508 16509 case 'function': 16510 return addInterceptor(exp, interceptorFn); 16511 16512 default: 16513 return addInterceptor(noop, interceptorFn); 16514 } 16515 } 16516 16517 function expressionInputDirtyCheck(newValue, oldValueOfValue, compareObjectIdentity) { 16518 16519 if (newValue == null || oldValueOfValue == null) { // null/undefined 16520 return newValue === oldValueOfValue; 16521 } 16522 16523 if (typeof newValue === 'object') { 16524 16525 // attempt to convert the value to a primitive type 16526 // TODO(docs): add a note to docs that by implementing valueOf even objects and arrays can 16527 // be cheaply dirty-checked 16528 newValue = getValueOf(newValue); 16529 16530 if (typeof newValue === 'object' && !compareObjectIdentity) { 16531 // objects/arrays are not supported - deep-watching them would be too expensive 16532 return false; 16533 } 16534 16535 // fall-through to the primitive equality check 16536 } 16537 16538 //Primitive or NaN 16539 // eslint-disable-next-line no-self-compare 16540 return newValue === oldValueOfValue || (newValue !== newValue && oldValueOfValue !== oldValueOfValue); 16541 } 16542 16543 function inputsWatchDelegate(scope, listener, objectEquality, parsedExpression, prettyPrintExpression) { 16544 var inputExpressions = parsedExpression.inputs; 16545 var lastResult; 16546 16547 if (inputExpressions.length === 1) { 16548 var oldInputValueOf = expressionInputDirtyCheck; // init to something unique so that equals check fails 16549 inputExpressions = inputExpressions[0]; 16550 return scope.$watch(function expressionInputWatch(scope) { 16551 var newInputValue = inputExpressions(scope); 16552 if (!expressionInputDirtyCheck(newInputValue, oldInputValueOf, inputExpressions.isPure)) { 16553 lastResult = parsedExpression(scope, undefined, undefined, [newInputValue]); 16554 oldInputValueOf = newInputValue && getValueOf(newInputValue); 16555 } 16556 return lastResult; 16557 }, listener, objectEquality, prettyPrintExpression); 16558 } 16559 16560 var oldInputValueOfValues = []; 16561 var oldInputValues = []; 16562 for (var i = 0, ii = inputExpressions.length; i < ii; i++) { 16563 oldInputValueOfValues[i] = expressionInputDirtyCheck; // init to something unique so that equals check fails 16564 oldInputValues[i] = null; 16565 } 16566 16567 return scope.$watch(function expressionInputsWatch(scope) { 16568 var changed = false; 16569 16570 for (var i = 0, ii = inputExpressions.length; i < ii; i++) { 16571 var newInputValue = inputExpressions[i](scope); 16572 if (changed || (changed = !expressionInputDirtyCheck(newInputValue, oldInputValueOfValues[i], inputExpressions[i].isPure))) { 16573 oldInputValues[i] = newInputValue; 16574 oldInputValueOfValues[i] = newInputValue && getValueOf(newInputValue); 16575 } 16576 } 16577 16578 if (changed) { 16579 lastResult = parsedExpression(scope, undefined, undefined, oldInputValues); 16580 } 16581 16582 return lastResult; 16583 }, listener, objectEquality, prettyPrintExpression); 16584 } 16585 16586 function oneTimeWatchDelegate(scope, listener, objectEquality, parsedExpression, prettyPrintExpression) { 16587 var unwatch, lastValue; 16588 if (parsedExpression.inputs) {
16589 unwatch = inputsWatchDelegate(scope, oneTimeListener, objectEquality, parsedExpression, prettyPrintExpression); 16590 } else { 16591 unwatch = scope.$watch(oneTimeWatch, oneTimeListener, objectEquality); 16592 } 16593 return unwatch; 16594 16595 function oneTimeWatch(scope) { 16596 return parsedExpression(scope); 16597 } 16598 function oneTimeListener(value, old, scope) { 16599 lastValue = value; 16600 if (isFunction(listener)) { 16601 listener(value, old, scope); 16602 } 16603 if (isDefined(value)) { 16604 scope.$$postDigest(function() { 16605 if (isDefined(lastValue)) { 16606 unwatch(); 16607 } 16608 }); 16609 } 16610 } 16611 } 16612 16613 function oneTimeLiteralWatchDelegate(scope, listener, objectEquality, parsedExpression) { 16614 var unwatch, lastValue; 16615 unwatch = scope.$watch(function oneTimeWatch(scope) { 16616 return parsedExpression(scope); 16617 }, function oneTimeListener(value, old, scope) { 16618 lastValue = value; 16619 if (isFunction(listener)) { 16620 listener(value, old, scope); 16621 } 16622 if (isAllDefined(value)) { 16623 scope.$$postDigest(function() { 16624 if (isAllDefined(lastValue)) unwatch(); 16625 }); 16626 } 16627 }, objectEquality); 16628 16629 return unwatch; 16630 16631 function isAllDefined(value) { 16632 var allDefined = true; 16633 forEach(value, function(val) { 16634 if (!isDefined(val)) allDefined = false; 16635 }); 16636 return allDefined; 16637 } 16638 } 16639 16640 function constantWatchDelegate(scope, listener, objectEquality, parsedExpression) { 16641 var unwatch = scope.$watch(function constantWatch(scope) { 16642 unwatch(); 16643 return parsedExpression(scope); 16644 }, listener, objectEquality); 16645 return unwatch; 16646 } 16647 16648 function addInterceptor(parsedExpression, interceptorFn) { 16649 if (!interceptorFn) return parsedExpression; 16650 var watchDelegate = parsedExpression.$$watchDelegate; 16651 var useInputs = false; 16652 16653 var regularWatch = 16654 watchDelegate !== oneTimeLiteralWatchDelegate && 16655 watchDelegate !== oneTimeWatchDelegate; 16656 16657 var fn = regularWatch ? function regularInterceptedExpression(scope, locals, assign, inputs) { 16658 var value = useInputs && inputs ? inputs[0] : parsedExpression(scope, locals, assign, inputs); 16659 return interceptorFn(value, scope, locals); 16660 } : function oneTimeInterceptedExpression(scope, locals, assign, inputs) { 16661 var value = parsedExpression(scope, locals, assign, inputs); 16662 var result = interceptorFn(value, scope, locals); 16663 // we only return the interceptor's result if the 16664 // initial value is defined (for bind-once) 16665 return isDefined(value) ? result : value; 16666 }; 16667 16668 // Propagate $$watchDelegates other then inputsWatchDelegate 16669 useInputs = !parsedExpression.inputs; 16670 if (watchDelegate && watchDelegate !== inputsWatchDelegate) { 16671 fn.$$watchDelegate = watchDelegate; 16672 fn.inputs = parsedExpression.inputs; 16673 } else if (!interceptorFn.$stateful) { 16674 // Treat interceptor like filters - assume non-stateful by default and use the inputsWatchDelegate 16675 fn.$$watchDelegate = inputsWatchDelegate; 16676 fn.inputs = parsedExpression.inputs ? parsedExpression.inputs : [parsedExpression]; 16677 } 16678 16679 if (fn.inputs) { 16680 fn.inputs = fn.inputs.map(function(e) { 16681 // Remove the isPure flag of inputs when it is not absolute because they are now wrapped in a 16682 // potentially non-pure interceptor function. 16683 if (e.isPure === PURITY_RELATIVE) { 16684 return function depurifier(s) { return e(s); }; 16685 } 16686 return e; 16687 }); 16688 } 16689 16690 return fn; 16691 } 16692 }]; 16693} 16694 16695/** 16696 * @ngdoc service 16697 * @name $q 16698 * @requires $rootScope 16699 * 16700 * @description 16701 * A service that helps you run functions asynchronously, and use their return values (or exceptions) 16702 * when they are done processing. 16703 * 16704 * This is a [Promises/A+](https://promisesaplus.com/)-compliant implementation of promises/deferred 16705 * objects inspired by [Kris Kowal's Q](https://github.com/kriskowal/q). 16706 * 16707 * $q can be used in two fashions --- one which is more similar to Kris Kowal's Q or jQuery's Deferred 16708 * implementations, and the other which resembles ES6 (ES2015) promises to
16708some degree. 16709 * 16710 * # $q constructor 16711 * 16712 * The streamlined ES6 style promise is essentially just using $q as a constructor which takes a `resolver` 16713 * function as the first argument. This is similar to the native Promise implementation from ES6, 16714 * see [MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise). 16715 * 16716 * While the constructor-style use is supported, not all of the supporting methods from ES6 promises are 16717 * available yet. 16718 * 16719 * It can be used like so: 16720 * 16721 * ```js 16722 * // for the purpose of this example let's assume that variables `$q` and `okToGreet` 16723 * // are available in the current lexical scope (they could have been injected or passed in). 16724 * 16725 * function asyncGreet(name) { 16726 * // perform some asynchronous operation, resolve or reject the promise when appropriate. 16727 * return $q(function(resolve, reject) { 16728 * setTimeout(function() { 16729 * if (okToGreet(name)) { 16730 * resolve('Hello, ' + name + '!'); 16731 * } else { 16732 * reject('Greeting ' + name + ' is not allowed.'); 16733 * } 16734 * }, 1000); 16735 * }); 16736 * } 16737 * 16738 * var promise = asyncGreet('Robin Hood'); 16739 * promise.then(function(greeting) { 16740 * alert('Success: ' + greeting); 16741 * }, function(reason) { 16742 * alert('Failed: ' + reason); 16743 * }); 16744 * ``` 16745 * 16746 * Note: progress/notify callbacks are not currently supported via the ES6-style interface. 16747 * 16748 * Note: unlike ES6 behavior, an exception thrown in the constructor function will NOT implicitly reject the promise. 16749 * 16750 * However, the more traditional CommonJS-style usage is still available, and documented below. 16751 * 16752 * [The CommonJS Promise proposal](http://wiki.commonjs.org/wiki/Promises) describes a promise as an 16753 * interface for interacting with an object that represents the result of an action that is 16754 * performed asynchronously, and may or may not be finished at any given point in time. 16755 * 16756 * From the perspective of dealing with error handling, deferred and promise APIs are to 16757 * asynchronous programming what `try`, `catch` and `throw` keywords are to synchronous programming. 16758 * 16759 * ```js 16760 * // for the purpose of this example let's assume that variables `$q` and `okToGreet` 16761 * // are available in the current lexical scope (they could have been injected or passed in). 16762 * 16763 * function asyncGreet(name) { 16764 * var deferred = $q.defer(); 16765 * 16766 * setTimeout(function() { 16767 * deferred.notify('About to greet ' + name + '.'); 16768 * 16769 * if (okToGreet(name)) { 16770 * deferred.resolve('Hello, ' + name + '!'); 16771 * } else { 16772 * deferred.reject('Greeting ' + name + ' is not allowed.'); 16773 * } 16774 * }, 1000); 16775 * 16776 * return deferred.promise; 16777 * } 16778 * 16779 * var promise = asyncGreet('Robin Hood'); 16780 * promise.then(function(greeting) { 16781 * alert('Success: ' + greeting); 16782 * }, function(reason) { 16783 * alert('Failed: ' + reason); 16784 * }, function(update) { 16785 * alert('Got notification: ' + update); 16786 * }); 16787 * ``` 16788 * 16789 * At first it might not be obvious why this extra complexity is worth the trouble. The payoff 16790 * comes in the way of guarantees that promise and deferred APIs make, see 16791 * https://github.com/kriskowal/uncommonjs/blob/master/promises/specification.md. 16792 * 16793 * Additionally the promise api allows for composition that is very hard to do with the 16794 * traditional callback ([CPS](http://en.wikipedia.org/wiki/Continuation-passing_style)) approach. 16795 * For more on this please see the [Q documentation](https://github.com/kriskowal/q) especially the 16796 * section on serial or parallel joining of promises. 16797 * 16798 * # The Deferred API 16799 * 16800 * A new instance of deferred is constructed by calling `$q.defer()`. 16801 * 16802 * The purpose of the deferred object is to expose the associated Promise instance as well as APIs 16803 * that can be used for signaling the successful or unsuccessful completion, as well as the status 16804 * of the task. 16805 * 16806 * **Methods** 16807 * 16808 * - `resolve(value)` – resolves the derived promise with the `value`. If the value is a rejection 16809 * constructed via `$q.reject`, the promise will be rejected instead. 16810 * - `reject(reason)` – rejects the derived promise with the `reason`. This is equivalent to 16811 * resolving it with a rejection constructed via `$q.reject`. 16812 * - `notify(value)` - provides updates on the status of the promise's execution. This may be called 16813 * multiple times before the promise is either resolved or rejected. 16814 * 16815 * **Properties** 16816 * 16817 * - promise – `{Promise}` – promise object associated with this deferred. 16818 * 16819 * 16820 * # The Promise API 16821 * 16822 * A new promise instance is created when a deferred instance is created and can be retrieved by 16823 * calling `deferred.promise`. 16824 * 16825 * The purpose of the promise object is to allow for interested parties to get access to the result 16826 * of the deferred task when it completes. 16827 * 16828 * **Methods** 16829 * 16830 * - `then(successCallback, [errorCallback], [notifyCallback])` – regardless of when the promise was or 16831 * will be resolved or rejected, `then` calls one of the success or error callbacks asynchronously 16832 * as soon as the result is available. The callbacks are called with a single argument: the result 16833 * or rejection reason. Additionally, the notify callback may be called zero or more times to 16834 * provide a progress indication, before the promise is resolved or rejected. 16835 * 16836 * This method *returns a new promise* which is resolved or rejected via the return value of the 16837 * `successCallback`, `errorCallback` (unless that value is a promise, in which case it is resolved
16838 * with the value which is resolved in that promise using 16839 * [promise chaining](http://www.html5rocks.com/en/tutorials/es6/promises/#toc-promises-queues)). 16840 * It also notifies via the return value of the `notifyCallback` method. The promise cannot be 16841 * resolved or rejected from the notifyCallback method. The errorCallback and notifyCallback 16842 * arguments are optional. 16843 * 16844 * - `catch(errorCallback)` – shorthand for `promise.then(null, errorCallback)` 16845 * 16846 * - `finally(callback, notifyCallback)` – allows you to observe either the fulfillment or rejection of a promise, 16847 * but to do so without modifying the final value. This is useful to release resources or do some 16848 * clean-up that needs to be done whether the promise was rejected or resolved. See the [full 16849 * specification](https://github.com/kriskowal/q/wiki/API-Reference#promisefinallycallback) for 16850 * more information. 16851 * 16852 * # Chaining promises 16853 * 16854 * Because calling the `then` method of a promise returns a new derived promise, it is easily 16855 * possible to create a chain of promises: 16856 * 16857 * ```js 16858 * promiseB = promiseA.then(function(result) { 16859 * return result + 1; 16860 * }); 16861 * 16862 * // promiseB will be resolved immediately after promiseA is resolved and its value 16863 * // will be the result of promiseA incremented by 1 16864 * ``` 16865 * 16866 * It is possible to create chains of any length and since a promise can be resolved with another 16867 * promise (which will defer its resolution further), it is possible to pause/defer resolution of 16868 * the promises at any point in the chain. This makes it possible to implement powerful APIs like 16869 * $http's response interceptors. 16870 * 16871 * 16872 * # Differences between Kris Kowal's Q and $q 16873 * 16874 * There are two main differences: 16875 * 16876 * - $q is integrated with the {@link ng.$rootScope.Scope} Scope model observation 16877 * mechanism in angular, which means faster propagation of resolution or rejection into your 16878 * models and avoiding unnecessary browser repaints, which would result in flickering UI. 16879 * - Q has many more features than $q, but that comes at a cost of bytes. $q is tiny, but contains
16880 * all the important functionality needed for common async tasks. 16881 * 16882 * # Testing 16883 * 16884 * ```js 16885 * it('should simulate promise', inject(function($q, $rootScope) { 16886 * var deferred = $q.defer(); 16887 * var promise = deferred.promise; 16888 * var resolvedValue; 16889 * 16890 * promise.then(function(value) { resolvedValue = value; }); 16891 * expect(resolvedValue).toBeUndefined(); 16892 * 16893 * // Simulate resolving of promise 16894 * deferred.resolve(123); 16895 * // Note that the 'then' function does not get called synchronously. 16896 * // This is because we want the promise API to always be async, whether or not 16897 * // it got called synchronously or asynchronously. 16898 * expect(resolvedValue).toBeUndefined(); 16899 * 16900 * // Propagate promise resolution to 'then' functions using $apply(). 16901 * $rootScope.$apply(); 16902 * expect(resolvedValue).toEqual(123); 16903 * })); 16904 * ``` 16905 * 16906 * @param {function(function, function)} resolver Function which is responsible for resolving or 16907 * rejecting the newly created promise. The first parameter is a function which resolves the 16908 * promise, the second parameter is a function which rejects the promise. 16909 * 16910 * @returns {Promise} The newly created promise. 16911 */ 16912/** 16913 * @ngdoc provider 16914 * @name $qProvider 16915 * @this 16916 * 16917 * @description 16918 */ 16919function $QProvider() { 16920 var errorOnUnhandledRejections = true; 16921 this.$get = ['$rootScope', '$exceptionHandler', function($rootScope, $exceptionHandler) { 16922 return qFactory(function(callback) { 16923 $rootScope.$evalAsync(callback); 16924 }, $exceptionHandler, errorOnUnhandledRejections); 16925 }]; 16926 16927 /** 16928 * @ngdoc method 16929 * @name $qProvider#errorOnUnhandledRejections 16930 * @kind function 16931 * 16932 * @description 16933 * Retrieves or overrides whether to generate an error when a rejected promise is not handled. 16934 * This feature is enabled by default. 16935 * 16936 * @param {boolean=} value Whether to generate an error when a rejected promise is not handled. 16937 * @returns {boolean|ng.$qProvider} Current value when called without a new value or self for 16938 * chaining otherwise. 16939 */ 16940 this.errorOnUnhandledRejections = function(value) { 16941 if (isDefined(value)) { 16942 errorOnUnhandledRejections = value; 16943 return this; 16944 } else { 16945 return errorOnUnhandledRejections; 16946 } 16947 }; 16948} 16949 16950/** @this */ 16951function $$QProvider() { 16952 var errorOnUnhandledRejections = true; 16953 this.$get = ['$browser', '$exceptionHandler', function($browser, $exceptionHandler) { 16954 return qFactory(function(callback) { 16955 $browser.defer(callback); 16956 }, $exceptionHandler, errorOnUnhandledRejections); 16957 }]; 16958 16959 this.errorOnUnhandledRejections = function(value) { 16960 if (isDefined(value)) { 16961 errorOnUnhandledRejections = value; 16962 return this; 16963 } else { 16964 return errorOnUnhandledRejections; 16965 } 16966 }; 16967} 16968 16969/** 16970 * Constructs a promise manager. 16971 * 16972 * @param {function(function)} nextTick Function for executing functions in the next turn. 16973 * @param {function(...*)} exceptionHandler Function into which unexpected exceptions are passed for 16974 * debugging purposes. 16975 * @param {boolean=} errorOnUnhandledRejections Whether an error should be generated on unhandled 16976 * promises rejections. 16977 * @returns {object} Promise manager. 16978 */ 16979function qFactory(nextTick, exceptionHandler, errorOnUnhandledRejections) { 16980 var $qMinErr = minErr('$q', TypeError); 16981 var queueSize = 0; 16982 var checkQueue = []; 16983 16984 /** 16985 * @ngdoc method 16986 * @name ng.$q#defer 16987 * @kind function 16988 * 16989 * @description 16990 * Creates a `Deferred` object which represents a task which will finish in the future. 16991 * 16992 * @returns {Deferred} Returns a new instance of deferred. 16993 */ 16994 function defer() { 16995 return new Deferred(); 16996 } 16997 16998 function Deferred() { 16999 var promise = this.promise = new Promise(); 17000 //Non prototype methods necessary to support unbound execution :/ 17001 this.resolve = function(val) { resolvePromise(promise, val); }; 17002 this.reject = function(reason) { rejectPromise(promise, reason); }; 17003 this.notify = function(progress) { notifyPromise(promise, progress); }; 17004 } 17005 17006 17007 function Promise() { 17008 this.$$state = { status: 0 }; 17009 } 17010 17011 extend(Promise.prototype, { 17012 then: function(onFulfilled, onRejected, progressBack) { 17013 if (isUndefined(onFulfilled) && isUndefined(onRejected) && isUndefined(progressBack)) { 17014 return this; 17015 } 17016 var result = new Promise(); 17017 17018 this.$$state.pending = this.$$state.pending || []; 17019 this.$$state.pending.push([result, onFulfilled, onRejected, progressBack]);
vendor: 5,220 bytes, lines 17020-17195
17020 if (this.$$state.status > 0) scheduleProcessQueue(this.$$state); 17021 17022 return result; 17023 }, 17024 17025 'catch': function(callback) { 17026 return this.then(null, callback); 17027 }, 17028 17029 'finally': function(callback, progressBack) { 17030 return this.then(function(value) { 17031 return handleCallback(value, resolve, callback); 17032 }, function(error) { 17033 return handleCallback(error, reject, callback); 17034 }, progressBack); 17035 } 17036 }); 17037 17038 function processQueue(state) { 17039 var fn, promise, pending; 17040 17041 pending = state.pending; 17042 state.processScheduled = false; 17043 state.pending = undefined; 17044 try { 17045 for (var i = 0, ii = pending.length; i < ii; ++i) { 17046 markQStateExceptionHandled(state); 17047 promise = pending[i][0]; 17048 fn = pending[i][state.status]; 17049 try { 17050 if (isFunction(fn)) { 17051 resolvePromise(promise, fn(state.value)); 17052 } else if (state.status === 1) { 17053 resolvePromise(promise, state.value); 17054 } else { 17055 rejectPromise(promise, state.value); 17056 } 17057 } catch (e) { 17058 rejectPromise(promise, e); 17059 } 17060 } 17061 } finally { 17062 --queueSize; 17063 if (errorOnUnhandledRejections && queueSize === 0) { 17064 nextTick(processChecks); 17065 } 17066 } 17067 } 17068 17069 function processChecks() { 17070 // eslint-disable-next-line no-unmodified-loop-condition 17071 while (!queueSize && checkQueue.length) { 17072 var toCheck = checkQueue.shift(); 17073 if (!isStateExceptionHandled(toCheck)) { 17074 markQStateExceptionHandled(toCheck); 17075 var errorMessage = 'Possibly unhandled rejection: ' + toDebugString(toCheck.value); 17076 if (isError(toCheck.value)) { 17077 exceptionHandler(toCheck.value, errorMessage); 17078 } else { 17079 exceptionHandler(errorMessage); 17080 } 17081 } 17082 } 17083 } 17084 17085 function scheduleProcessQueue(state) { 17086 if (errorOnUnhandledRejections && !state.pending && state.status === 2 && !isStateExceptionHandled(state)) { 17087 if (queueSize === 0 && checkQueue.length === 0) { 17088 nextTick(processChecks); 17089 } 17090 checkQueue.push(state); 17091 } 17092 if (state.processScheduled || !state.pending) return; 17093 state.processScheduled = true; 17094 ++queueSize; 17095 nextTick(function() { processQueue(state); }); 17096 } 17097 17098 function resolvePromise(promise, val) { 17099 if (promise.$$state.status) return; 17100 if (val === promise) { 17101 $$reject(promise, $qMinErr( 17102 'qcycle', 17103 'Expected promise to be resolved with value other than itself \'{0}\'', 17104 val)); 17105 } else { 17106 $$resolve(promise, val); 17107 } 17108 17109 } 17110 17111 function $$resolve(promise, val) { 17112 var then; 17113 var done = false; 17114 try { 17115 if (isObject(val) || isFunction(val)) then = val.then; 17116 if (isFunction(then)) { 17117 promise.$$state.status = -1; 17118 then.call(val, doResolve, doReject, doNotify); 17119 } else { 17120 promise.$$state.value = val; 17121 promise.$$state.status = 1; 17122 scheduleProcessQueue(promise.$$state); 17123 } 17124 } catch (e) { 17125 doReject(e); 17126 } 17127 17128 function doResolve(val) { 17129 if (done) return; 17130 done = true; 17131 $$resolve(promise, val); 17132 } 17133 function doReject(val) { 17134 if (done) return; 17135 done = true; 17136 $$reject(promise, val); 17137 } 17138 function doNotify(progress) { 17139 notifyPromise(promise, progress); 17140 } 17141 } 17142 17143 function rejectPromise(promise, reason) { 17144 if (promise.$$state.status) return; 17145 $$reject(promise, reason); 17146 } 17147 17148 function $$reject(promise, reason) { 17149 promise.$$state.value = reason; 17150 promise.$$state.status = 2; 17151 scheduleProcessQueue(promise.$$state); 17152 } 17153 17154 function notifyPromise(promise, progress) { 17155 var callbacks = promise.$$state.pending; 17156 17157 if ((promise.$$state.status <= 0) && callbacks && callbacks.length) { 17158 nextTick(function() { 17159 var callback, result; 17160 for (var i = 0, ii = callbacks.length; i < ii; i++) { 17161 result = callbacks[i][0]; 17162 callback = callbacks[i][3]; 17163 try { 17164 notifyPromise(result, isFunction(callback) ? callback(progress) : progress); 17165 } catch (e) { 17166 exceptionHandler(e); 17167 } 17168 } 17169 }); 17170 } 17171 } 17172 17173 /** 17174 * @ngdoc method 17175 * @name $q#reject 17176 * @kind function 17177 * 17178 * @description 17179 * Creates a promise that is resolved as rejected with the specified `reason`. This api should be 17180 * used to forward rejection in a chain of promises. If you are dealing with the last promise in 17181 * a promise chain, you don't need to worry about it. 17182 * 17183 * When comparing deferreds/promises to the familiar behavior of try/catch/throw, think of 17184 * `reject` as the `throw` keyword in JavaScript. This also means that if you "catch" an error via 17185 * a promise error callback and you want to forward the error to the promise derived from the 17186 * current promise, you have to "rethrow" the error by returning a rejection constructed via 17187 * `reject`. 17188 * 17189 * ```js 17190 * promiseB = promiseA.then(function(result) { 17191 * // success: do something and resolve promiseB 17192 * // with the old or a new result 17193 * return result; 17194 * }, function(reason) { 17195 * // error: handle the error if possible and
17196 * // resolve promiseB with newPromiseOrValue, 17197 * // otherwise forward the rejection to promiseB 17198 * if (canHandle(reason)) { 17199 * // handle the error and recover 17200 * return newPromiseOrValue; 17201 * } 17202 * return $q.reject(reason); 17203 * }); 17204 * ``` 17205 * 17206 * @param {*} reason Constant, message, exception or an object representing the rejection reason. 17207 * @returns {Promise} Returns a promise that was already resolved as rejected with the `reason`. 17208 */ 17209 function reject(reason) { 17210 var result = new Promise(); 17211 rejectPromise(result, reason); 17212 return result; 17213 } 17214 17215 function handleCallback(value, resolver, callback) { 17216 var callbackOutput = null; 17217 try { 17218 if (isFunction(callback)) callbackOutput = callback(); 17219 } catch (e) { 17220 return reject(e); 17221 } 17222 if (isPromiseLike(callbackOutput)) { 17223 return callbackOutput.then(function() { 17224 return resolver(value); 17225 }, reject); 17226 } else { 17227 return resolver(value); 17228 } 17229 } 17230 17231 /** 17232 * @ngdoc method 17233 * @name $q#when 17234 * @kind function 17235 * 17236 * @description 17237 * Wraps an object that might be a value or a (3rd party) then-able promise into a $q promise. 17238 * This is useful when you are dealing with an object that might or might not be a promise, or if 17239 * the promise comes from a source that can't be trusted. 17240 * 17241 * @param {*} value Value or a promise 17242 * @param {Function=} successCallback 17243 * @param {Function=} errorCallback 17244 * @param {Function=} progressCallback 17245 * @returns {Promise} Returns a promise of the passed value or promise 17246 */ 17247 17248 17249 function when(value, callback, errback, progressBack) { 17250 var result = new Promise(); 17251 resolvePromise(result, value); 17252 return result.then(callback, errback, progressBack); 17253 } 17254 17255 /** 17256 * @ngdoc method 17257 * @name $q#resolve 17258 * @kind function 17259 * 17260 * @description 17261 * Alias of {@link ng.$q#when when} to maintain naming consistency with ES6. 17262 * 17263 * @param {*} value Value or a promise 17264 * @param {Function=} successCallback 17265 * @param {Function=} errorCallback 17266 * @param {Function=} progressCallback 17267 * @returns {Promise} Returns a promise of the passed value or promise 17268 */ 17269 var resolve = when; 17270 17271 /** 17272 * @ngdoc method 17273 * @name $q#all 17274 * @kind function 17275 * 17276 * @description 17277 * Combines multiple promises into a single promise that is resolved when all of the input 17278 * promises are resolved. 17279 * 17280 * @param {Array.<Promise>|Object.<Promise>} promises An array or hash of promises. 17281 * @returns {Promise} Returns a single promise that will be resolved with an array/hash of values, 17282 * each value corresponding to the promise at the same index/key in the `promises` array/hash. 17283 * If any of the promises is resolved with a rejection, this resulting promise will be rejected 17284 * with the same rejection value. 17285 */ 17286 17287 function all(promises) { 17288 var result = new Promise(), 17289 counter = 0, 17290 results = isArray(promises) ? [] : {}; 17291 17292 forEach(promises, function(promise, key) { 17293 counter++; 17294 when(promise).then(function(value) { 17295 results[key] = value; 17296 if (!(--counter)) resolvePromise(result, results); 17297 }, function(reason) { 17298 rejectPromise(result, reason); 17299 }); 17300 }); 17301 17302 if (counter === 0) { 17303 resolvePromise(result, results); 17304 } 17305 17306 return result; 17307 } 17308 17309 /** 17310 * @ngdoc method 17311 * @name $q#race 17312 * @kind function 17313 * 17314 * @description 17315 * Returns a promise that resolves or rejects as soon as one of those promises 17316 * resolves or rejects, with the value or reason from that promise. 17317 * 17318 * @param {Array.<Promise>|Object.<Promise>} promises An array or hash of promises. 17319 * @returns {Promise} a promise that resolves or rejects as soon as one of the `promises` 17320 * resolves or rejects, with the value or reason from that promise. 17321 */ 17322 17323 function race(promises) { 17324 var deferred = defer(); 17325 17326 forEach(promises, function(promise) { 17327 when(promise).then(deferred.resolve, deferred.reject); 17328 }); 17329 17330 return deferred.promise; 17331 } 17332 17333 function $Q(resolver) { 17334 if (!isFunction(resolver)) { 17335 throw $qMinErr('norslvr', 'Expected resolverFn, got \'{0}\'', resolver); 17336 } 17337 17338 var promise = new Promise(); 17339 17340 function resolveFn(value) { 17341 resolvePromise(promise, value); 17342 } 17343 17344 function rejectFn(reason) { 17345 rejectPromise(promise, reason); 17346 } 17347 17348 resolver(resolveFn, rejectFn); 17349 17350 return promise; 17351 } 17352 17353 // Let's make the instanceof operator work for promises, so that 17354 // `new $q(fn) instanceof $q` would evaluate to true. 17355 $Q.prototype = Promise.prototype; 17356 17357 $Q.defer = defer; 17358 $Q.reject = reject; 17359 $Q.when = when; 17360 $Q.resolve = resolve; 17361 $Q.all = all; 17362 $Q.race = race; 17363 17364 return $Q; 17365} 17366 17367function isStateExceptionHandled(state) { 17368 return !!state.pur; 17369} 17370function markQStateExceptionHandled(state) { 17371 state.pur = true; 17372} 17373function markQExceptionHandled(q) { 17374 markQStateExceptionHandled(q.$$state); 17375} 17376 17377/** @this */ 17378function $$RAFProvider() { //rAF 17379 this.$get = ['$window', '$timeout', function($window, $timeout) { 17380 var requestAnimationFrame = $window.requestAnimationFrame || 17381 $window.webkitRequestAnimationFrame; 17382 17383 var cancelAnimationFrame = $window.cancelAnimationFrame || 17384 $window.webkitCancelAnimationFrame || 17385 $window.webkitCancelRequestAnimationFrame; 17386 17387 var rafSupported = !!requestAnimationFrame; 17388 var raf = rafSupported 17389 ? function(fn) { 17390 var id = requestAnimationFrame(fn); 17391 return function() { 17392 cancelAnimationFrame(id); 17393 }; 17394 } 17395 : function(fn) { 17396 var timer = $timeout(fn, 16.66, false); // 1000 / 60 = 16.666 17397 return function() { 17398 $timeout.cancel(timer); 17399 }; 17400 }; 17401 17402 raf.supported = rafSupported; 17403 17404 return raf; 17405 }]; 17406} 17407 17408/** 17409 * DESIGN NOTES 17410 * 17411 * The design decisions behind the scope are heavily favored for speed and memory consumption. 17412 * 17413 * The typical use of scope is to watch the expressions, which most of the time return the same 17414 * value as last time so we optimize the operation. 17415 * 17416 * Closures construction is expensive in terms of speed as well as memory: 17417 * - No closures, instead use prototypical inheritance for API 17418 * - Internal state needs to be stored on scope directly, which means that private state is 17419 * exposed as $$____ properties 17420 * 17421 * Loop operations are optimized by using while(count--) { ... } 17422 * - This means that in order to keep the same order of execution as addition we have to add 17423 * items to the array at the beginning (unshift) instead of at the end (push) 17424 * 17425 * Child scopes are created and removed often 17426 * - Using an array would be slow since inserts in the middle are expensive; so we use linked lists 17427 * 17428 * There are fewer watches than observers. This is why you don't want the observer to be implemented 17429 * in the same way as watch. Watch requires return of the initialization function which is expensive 17430 * to construct. 17431 */ 17432 17433 17434/** 17435 * @ngdoc provider 17436 * @name $rootScopeProvider 17437 * @description 17438 * 17439 * Provider for the $rootScope service. 17440 */ 17441 17442/** 17443 * @ngdoc method 17444 * @name $rootScopeProvider#digestTtl 17445 * @description 17446 * 17447 * Sets the number of `$digest` iterations the scope should attempt to execute before giving up and 17448 * assuming that the model is unstable. 17449 * 17450 * The current default is 10 iterations. 17451 * 17452 * In complex applications it's possible that the dependencies between `$watch`s will result in 17453 * several digest iterations. However if an application needs more than the default 10 digest 17454 * iterations for its model to stabilize then you should investigate what is causing the model to 17455 * continuously change during the digest. 17456 * 17457 * Increasing the TTL could have performance implications, so you should not change it without 17458 * proper justification. 17459 * 17460 * @param {number} limit The number of digest iterations. 17461 */ 17462 17463 17464/** 17465 * @ngdoc service 17466 * @name $rootScope 17467 * @this 17468 * 17469 * @description 17470 * 17471 * Every application has a single root {@link ng.$rootScope.Scope scope}. 17472 * All other scopes are descendant scopes of the root scope. Scopes provide separation 17473 * between the model and the view, via a mechanism for watching the model for changes. 17474 * They also provide event emission/broadcast and subscription facility. See the 17475 * {@link guide/scope developer guide on scopes}. 17476 */ 17477function $RootScopeProvider() { 17478 var TTL = 10; 17479 var $rootScopeMinErr = minErr('$rootScope'); 17480 var lastDirtyWatch = null; 17481 var applyAsyncId = null; 17482 17483 this.digestTtl = function(value) { 17484 if (arguments.length) { 17485 TTL = value; 17486 } 17487 return TTL; 17488 }; 17489 17490 function createChildScopeClass(parent) { 17491 function ChildScope() {
vendor: 11,072 bytes, lines 17492-17752
17492 this.$$watchers = this.$$nextSibling = 17493 this.$$childHead = this.$$childTail = null; 17494 this.$$listeners = {}; 17495 this.$$listenerCount = {}; 17496 this.$$watchersCount = 0; 17497 this.$id = nextUid(); 17498 this.$$ChildScope = null; 17499 } 17500 ChildScope.prototype = parent; 17501 return ChildScope; 17502 } 17503 17504 this.$get = ['$exceptionHandler', '$parse', '$browser', 17505 function($exceptionHandler, $parse, $browser) { 17506 17507 function destroyChildScope($event) { 17508 $event.currentScope.$$destroyed = true; 17509 } 17510 17511 function cleanUpScope($scope) { 17512 17513 // Support: IE 9 only 17514 if (msie === 9) { 17515 // There is a memory leak in IE9 if all child scopes are not disconnected 17516 // completely when a scope is destroyed. So this code will recurse up through 17517 // all this scopes children 17518 // 17519 // See issue https://github.com/angular/angular.js/issues/10706 17520 if ($scope.$$childHead) { 17521 cleanUpScope($scope.$$childHead); 17522 } 17523 if ($scope.$$nextSibling) { 17524 cleanUpScope($scope.$$nextSibling); 17525 } 17526 } 17527 17528 // The code below works around IE9 and V8's memory leaks 17529 // 17530 // See: 17531 // - https://code.google.com/p/v8/issues/detail?id=2073#c26 17532 // - https://github.com/angular/angular.js/issues/6794#issuecomment-38648909 17533 // - https://github.com/angular/angular.js/issues/1313#issuecomment-10378451 17534 17535 $scope.$parent = $scope.$$nextSibling = $scope.$$prevSibling = $scope.$$childHead = 17536 $scope.$$childTail = $scope.$root = $scope.$$watchers = null; 17537 } 17538 17539 /** 17540 * @ngdoc type 17541 * @name $rootScope.Scope 17542 * 17543 * @description 17544 * A root scope can be retrieved using the {@link ng.$rootScope $rootScope} key from the 17545 * {@link auto.$injector $injector}. Child scopes are created using the 17546 * {@link ng.$rootScope.Scope#$new $new()} method. (Most scopes are created automatically when 17547 * compiled HTML template is executed.) See also the {@link guide/scope Scopes guide} for 17548 * an in-depth introduction and usage examples. 17549 * 17550 * 17551 * # Inheritance 17552 * A scope can inherit from a parent scope, as in this example: 17553 * ```js 17554 var parent = $rootScope; 17555 var child = parent.$new(); 17556 17557 parent.salutation = "Hello"; 17558 expect(child.salutation).toEqual('Hello'); 17559 17560 child.salutation = "Welcome"; 17561 expect(child.salutation).toEqual('Welcome'); 17562 expect(parent.salutation).toEqual('Hello'); 17563 * ``` 17564 * 17565 * When interacting with `Scope` in tests, additional helper methods are available on the 17566 * instances of `Scope` type. See {@link ngMock.$rootScope.Scope ngMock Scope} for additional 17567 * details. 17568 * 17569 * 17570 * @param {Object.<string, function()>=} providers Map of service factory which need to be 17571 * provided for the current scope. Defaults to {@link ng}. 17572 * @param {Object.<string, *>=} instanceCache Provides pre-instantiated services which should 17573 * append/override services provided by `providers`. This is handy 17574 * when unit-testing and having the need to override a default 17575 * service. 17576 * @returns {Object} Newly created scope. 17577 * 17578 */ 17579 function Scope() { 17580 this.$id = nextUid(); 17581 this.$$phase = this.$parent = this.$$watchers = 17582 this.$$nextSibling = this.$$prevSibling = 17583 this.$$childHead = this.$$childTail = null; 17584 this.$root = this; 17585 this.$$destroyed = false; 17586 this.$$listeners = {}; 17587 this.$$listenerCount = {}; 17588 this.$$watchersCount = 0; 17589 this.$$isolateBindings = null; 17590 } 17591 17592 /** 17593 * @ngdoc property 17594 * @name $rootScope.Scope#$id 17595 * 17596 * @description 17597 * Unique scope ID (monotonically increasing) useful for debugging. 17598 */ 17599 17600 /** 17601 * @ngdoc property 17602 * @name $rootScope.Scope#$parent 17603 * 17604 * @description 17605 * Reference to the parent scope. 17606 */ 17607 17608 /** 17609 * @ngdoc property 17610 * @name $rootScope.Scope#$root 17611 * 17612 * @description 17613 * Reference to the root scope. 17614 */ 17615 17616 Scope.prototype = { 17617 constructor: Scope, 17618 /** 17619 * @ngdoc method 17620 * @name $rootScope.Scope#$new 17621 * @kind function 17622 * 17623 * @description 17624 * Creates a new child {@link ng.$rootScope.Scope scope}. 17625 * 17626 * The parent scope will propagate the {@link ng.$rootScope.Scope#$digest $digest()} event. 17627 * The scope can be removed from the scope hierarchy using {@link ng.$rootScope.Scope#$destroy $destroy()}. 17628 * 17629 * {@link ng.$rootScope.Scope#$destroy $destroy()} must be called on a scope when it is 17630 * desired for the scope and its child scopes to be permanently detached from the parent and 17631 * thus stop participating in model change detection and listener notification by invoking. 17632 * 17633 * @param {boolean} isolate If true, then the scope does not prototypically inherit from the 17634 * parent scope. The scope is isolated, as it can not see parent scope properties. 17635 * When creating widgets, it is useful for the widget to not accidentally read parent 17636 * state. 17637 * 17638 * @param {Scope} [parent=this] The {@link ng.$rootScope.Scope `Scope`} that will be the `$parent` 17639 * of the newly created scope. Defaults to `this` scope if not provided. 17640 * This is used when creating a transclude scope to correctly place it 17641 * in the scope hierarchy while maintaining the correct prototypical 17642 * inheritance. 17643 * 17644 * @returns {Object} The newly created child scope. 17645 * 17646 */ 17647 $new: function(isolate, parent) { 17648 var child; 17649 17650 parent = parent || this; 17651 17652 if (isolate) { 17653 child = new Scope(); 17654 child.$root = this.$root; 17655 } else { 17656 // Only create a child scope class if somebody asks for one, 17657 // but cache it to allow the VM to optimize lookups. 17658 if (!this.$$ChildScope) { 17659 this.$$ChildScope = createChildScopeClass(this); 17660 } 17661 child = new this.$$ChildScope(); 17662 } 17663 child.$parent = parent; 17664 child.$$prevSibling = parent.$$childTail; 17665 if (parent.$$childHead) { 17666 parent.$$childTail.$$nextSibling = child; 17667 parent.$$childTail = child; 17668 } else { 17669 parent.$$childHead = parent.$$childTail = child; 17670 } 17671 17672 // When the new scope is not isolated or we inherit from `this`, and 17673 // the parent scope is destroyed, the property `$$destroyed` is inherited 17674 // prototypically. In all other cases, this property needs to be set 17675 // when the parent scope is destroyed. 17676 // The listener needs to be added after the parent is set 17677 if (isolate || parent !== this) child.$on('$destroy', destroyChildScope); 17678 17679 return child; 17680 }, 17681 17682 /** 17683 * @ngdoc method 17684 * @name $rootScope.Scope#$watch 17685 * @kind function 17686 * 17687 * @description 17688 * Registers a `listener` callback to be executed whenever the `watchExpression` changes. 17689 * 17690 * - The `watchExpression` is called on every call to {@link ng.$rootScope.Scope#$digest 17691 * $digest()} and should return the value that will be watched. (`watchExpression` should not change 17692 * its value when executed multiple times with the same input because it may be executed multiple 17693 * times by {@link ng.$rootScope.Scope#$digest $digest()}. That is, `watchExpression` should be 17694 * [idempotent](http://en.wikipedia.org/wiki/Idempotence).) 17695 * - The `listener` is called only when the value from the current `watchExpression` and the 17696 * previous call to `watchExpression` are not equal (with the exception of the initial run, 17697 * see below). Inequality is determined according to reference inequality, 17698 * [strict comparison](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Comparison_Operators) 17699 * via the `!==` Javascript operator, unless `objectEquality == true` 17700 * (see next point) 17701 * - When `objectEquality == true`, inequality of the `watchExpression` is determined 17702 * according to the {@link angular.equals} function. To save the value of the object for 17703 * later comparison, the {@link angular.copy} function is used. This therefore means that 17704 * watching complex objects will have adverse memory and performance implications. 17705 * - This should not be used to watch for changes in objects that are 17706 * or contain [File](https://developer.mozilla.org/docs/Web/API/File) objects due to limitations with {@link angular.copy `angular.copy`}. 17707 * - The watch `listener` may change the model, which may trigger other `listener`s to fire. 17708 * This is achieved by rerunning the watchers until no changes are detected. The rerun 17709 * iteration limit is 10 to prevent an infinite loop deadlock. 17710 * 17711 * 17712 * If you want to be notified whenever {@link ng.$rootScope.Scope#$digest $digest} is called, 17713 * you can register a `watchExpression` function with no `listener`. (Be prepared for 17714 * multiple calls to your `watchExpression` because it will execute multiple times in a 17715 * single {@link ng.$rootScope.Scope#$digest $digest} cycle if a change is detected.) 17716 * 17717 * After a watcher is registered with the scope, the `listener` fn is called asynchronously 17718 * (via {@link ng.$rootScope.Scope#$evalAsync $evalAsync}) to initialize the 17719 * watcher. In rare cases, this is undesirable because the listener is called when the result 17720 * of `watchExpression` didn't change. To detect this scenario within the `listener` fn, you 17721 * can compare the `newVal` and `oldVal`. If these two values are identical (`===`) then the 17722 * listener was called due to initialization. 17723 * 17724 * 17725 * 17726 * # Example 17727 * ```js 17728 // let's assume that scope was dependency injected as the $rootScope 17729 var scope = $rootScope; 17730 scope.name = 'misko'; 17731 scope.counter = 0; 17732 17733 expect(scope.counter).toEqual(0); 17734 scope.$watch('name', function(newValue, oldValue) { 17735 scope.counter = scope.counter + 1; 17736 }); 17737 expect(scope.counter).toEqual(0); 17738 17739 scope.$digest(); 17740 // the listener is always called during the first $digest loop after it was registered 17741 expect(scope.counter).toEqual(1); 17742 17743 scope.$digest(); 17744 // but now it will not be called unless the value changes 17745 expect(scope.counter).toEqual(1); 17746 17747 scope.name = 'adam'; 17748 scope.$digest(); 17749 expect(scope.counter).toEqual(2); 17750 17751 17752
17753 // Using a function as a watchExpression 17754 var food; 17755 scope.foodCounter = 0; 17756 expect(scope.foodCounter).toEqual(0); 17757 scope.$watch( 17758 // This function returns the value being watched. It is called for each turn of the $digest loop 17759 function() { return food; }, 17760 // This is the change listener, called when the value returned from the above function changes 17761 function(newValue, oldValue) { 17762 if ( newValue !== oldValue ) { 17763 // Only increment the counter if the value changed 17764 scope.foodCounter = scope.foodCounter + 1; 17765 } 17766 } 17767 ); 17768 // No digest has been run so the counter will be zero 17769 expect(scope.foodCounter).toEqual(0); 17770 17771 // Run the digest but since food has not changed count will still be zero 17772 scope.$digest(); 17773 expect(scope.foodCounter).toEqual(0); 17774 17775 // Update food and run digest. Now the counter will increment 17776 food = 'cheeseburger'; 17777 scope.$digest(); 17778 expect(scope.foodCounter).toEqual(1); 17779 17780 * ``` 17781 * 17782 * 17783 * 17784 * @param {(function()|string)} watchExpression Expression that is evaluated on each 17785 * {@link ng.$rootScope.Scope#$digest $digest} cycle. A change in the return value triggers 17786 * a call to the `listener`. 17787 * 17788 * - `string`: Evaluated as {@link guide/expression expression} 17789 * - `function(scope)`: called with current `scope` as a parameter. 17790 * @param {function(newVal, oldVal, scope)} listener Callback called whenever the value 17791 * of `watchExpression` changes. 17792 * 17793 * - `newVal` contains the current value of the `watchExpression` 17794 * - `oldVal` contains the previous value of the `watchExpression` 17795 * - `scope` refers to the current scope 17796 * @param {boolean=} [objectEquality=false] Compare for object equality using {@link angular.equals} instead of 17797 * comparing for reference equality. 17798 * @returns {function()} Returns a deregistration function for this listener. 17799 */ 17800 $watch: function(watchExp, listener, objectEquality, prettyPrintExpression) { 17801 var get = $parse(watchExp); 17802 17803 if (get.$$watchDelegate) { 17804 return get.$$watchDelegate(this, listener, objectEquality, get, watchExp); 17805 } 17806 var scope = this, 17807 array = scope.$$watchers, 17808 watcher = { 17809 fn: listener, 17810 last: initWatchVal, 17811 get: get, 17812 exp: prettyPrintExpression || watchExp, 17813 eq: !!objectEquality 17814 }; 17815 17816 lastDirtyWatch = null; 17817 17818 if (!isFunction(listener)) { 17819 watcher.fn = noop; 17820 } 17821 17822 if (!array) { 17823 array = scope.$$watchers = []; 17824 array.$$digestWatchIndex = -1; 17825 } 17826 // we use unshift since we use a while loop in $digest for speed. 17827 // the while loop reads in reverse order. 17828 array.unshift(watcher); 17829 array.$$digestWatchIndex++; 17830 incrementWatchersCount(this, 1); 17831 17832 return function deregisterWatch() { 17833 var index = arrayRemove(array, watcher); 17834 if (index >= 0) { 17835 incrementWatchersCount(scope, -1); 17836 if (index < array.$$digestWatchIndex) { 17837 array.$$digestWatchIndex--; 17838 } 17839 } 17840 lastDirtyWatch = null; 17841 }; 17842 }, 17843 17844 /** 17845 * @ngdoc method 17846 * @name $rootScope.Scope#$watchGroup 17847 * @kind function 17848 * 17849 * @description 17850 * A variant of {@link ng.$rootScope.Scope#$watch $watch()} where it watches an array of `watchExpressions`. 17851 * If any one expression in the collection changes the `listener` is executed. 17852 * 17853 * - The items in the `watchExpressions` array are observed via the standard `$watch` operation. Their return 17854 * values are examined for changes on every call to `$digest`. 17855 * - The `listener` is called whenever any expression in the `watchExpressions` array changes. 17856 * 17857 * `$watchGroup` is more performant than watching each expression individually, and should be 17858 * used when the listener does not need to know which expression has changed. 17859 * If the listener needs to know which expression has changed, 17860 * {@link ng.$rootScope.Scope#$watch $watch()} or 17861 * {@link ng.$rootScope.Scope#$watchCollection $watchCollection()} should be used. 17862 * 17863 * @param {Array.<string|Function(scope)>} watchExpressions Array of expressions that will be individually 17864 * watched using {@link ng.$rootScope.Scope#$watch $watch()} 17865 * 17866 * @param {function(newValues, oldValues, scope)} listener Callback called whenever the return value of any 17867 * expression in `watchExpressions` changes 17868 * The `newValues` array contains the current values of the `watchExpressions`, with the indexes matching 17869 * those of `watchExpression` 17870 * and the `oldValues` array contains the previous values of the `watchExpressions`, with the indexes matching 17871 * those of `watchExpression`. 17872 * 17873 * Note that `newValues` and `oldValues` reflect the differences in each **individual** 17874 * expression, and not the difference of the values between each call of the listener. 17875 * That means the difference between `newValues` and `oldValues` cannot be used to determine 17876 * which expression has changed / remained stable: 17877 * 17878 * ```js 17879 * 17880 * $scope.$watchGroup(['v1', 'v2'], function(newValues, oldValues) { 17881 * console.log(newValues, oldValues); 17882 * }); 17883 * 17884 * // newValues, oldValues initially 17885 * // [undefined, undefined], [undefined, undefined] 17886 * 17887 * $scope.v1 = 'a'; 17888 * $scope.v2 = 'a'; 17889 * 17890 * // ['a', 'a'], [undefined, undefined] 17891 * 17892 * $scope.v2 = 'b' 17893 * 17894 * // v1 hasn't changed since it became `'a'`, therefore its oldValue is still `undefined` 17895 * // ['a', 'b'], [undefined, 'a'] 17896 * 17897 * ``` 17898 * 17899 * The `scope` refers to the current scope. 17900 * @returns {function()} Returns a de-registration function for all listeners. 17901 */ 17902 $watchGroup: function(watchExpressions, listener) { 17903 var oldValues = new Array(watchExpressions.length); 17904 var newValues = new Array(watchExpressions.length); 17905 var deregisterFns = []; 17906 var self = this; 17907 var changeReactionScheduled = false;
vendor: 4,272 bytes, lines 17908-18017
17908 var firstRun = true; 17909 17910 if (!watchExpressions.length) { 17911 // No expressions means we call the listener ASAP 17912 var shouldCall = true; 17913 self.$evalAsync(function() { 17914 if (shouldCall) listener(newValues, newValues, self); 17915 }); 17916 return function deregisterWatchGroup() { 17917 shouldCall = false; 17918 }; 17919 } 17920 17921 if (watchExpressions.length === 1) { 17922 // Special case size of one 17923 return this.$watch(watchExpressions[0], function watchGroupAction(value, oldValue, scope) { 17924 newValues[0] = value; 17925 oldValues[0] = oldValue; 17926 listener(newValues, (value === oldValue) ? newValues : oldValues, scope); 17927 }); 17928 } 17929 17930 forEach(watchExpressions, function(expr, i) { 17931 var unwatchFn = self.$watch(expr, function watchGroupSubAction(value, oldValue) { 17932 newValues[i] = value; 17933 oldValues[i] = oldValue; 17934 if (!changeReactionScheduled) { 17935 changeReactionScheduled = true; 17936 self.$evalAsync(watchGroupAction); 17937 } 17938 }); 17939 deregisterFns.push(unwatchFn); 17940 }); 17941 17942 function watchGroupAction() { 17943 changeReactionScheduled = false; 17944 17945 if (firstRun) { 17946 firstRun = false; 17947 listener(newValues, newValues, self); 17948 } else { 17949 listener(newValues, oldValues, self); 17950 } 17951 } 17952 17953 return function deregisterWatchGroup() { 17954 while (deregisterFns.length) { 17955 deregisterFns.shift()(); 17956 } 17957 }; 17958 }, 17959 17960 17961 /** 17962 * @ngdoc method 17963 * @name $rootScope.Scope#$watchCollection 17964 * @kind function 17965 * 17966 * @description 17967 * Shallow watches the properties of an object and fires whenever any of the properties change 17968 * (for arrays, this implies watching the array items; for object maps, this implies watching 17969 * the properties). If a change is detected, the `listener` callback is fired. 17970 * 17971 * - The `obj` collection is observed via standard $watch operation and is examined on every 17972 * call to $digest() to see if any items have been added, removed, or moved. 17973 * - The `listener` is called whenever anything within the `obj` has changed. Examples include 17974 * adding, removing, and moving items belonging to an object or array. 17975 * 17976 * 17977 * # Example 17978 * ```js 17979 $scope.names = ['igor', 'matias', 'misko', 'james']; 17980 $scope.dataCount = 4; 17981 17982 $scope.$watchCollection('names', function(newNames, oldNames) { 17983 $scope.dataCount = newNames.length; 17984 }); 17985 17986 expect($scope.dataCount).toEqual(4); 17987 $scope.$digest(); 17988 17989 //still at 4 ... no changes 17990 expect($scope.dataCount).toEqual(4); 17991 17992 $scope.names.pop(); 17993 $scope.$digest(); 17994 17995 //now there's been a change 17996 expect($scope.dataCount).toEqual(3); 17997 * ``` 17998 * 17999 * 18000 * @param {string|function(scope)} obj Evaluated as {@link guide/expression expression}. The 18001 * expression value should evaluate to an object or an array which is observed on each 18002 * {@link ng.$rootScope.Scope#$digest $digest} cycle. Any shallow change within the 18003 * collection will trigger a call to the `listener`. 18004 * 18005 * @param {function(newCollection, oldCollection, scope)} listener a callback function called 18006 * when a change is detected. 18007 * - The `newCollection` object is the newly modified data obtained from the `obj` expression 18008 * - The `oldCollection` object is a copy of the former collection data. 18009 * Due to performance considerations, the`oldCollection` value is computed only if the 18010 * `listener` function declares two or more arguments. 18011 * - The `scope` argument refers to the current scope. 18012 * 18013 * @returns {function()} Returns a de-registration function for this listener. When the 18014 * de-registration function is executed, the internal watch operation is terminated. 18015 */ 18016 $watchCollection: function(obj, listener) { 18017 $watchCollectionInterceptor.$stateful = tru
vendor: 6,149 bytes, lines 18017-18175
18017e; 18018 18019 var self = this; 18020 // the current value, updated on each dirty-check run 18021 var newValue; 18022 // a shallow copy of the newValue from the last dirty-check run, 18023 // updated to match newValue during dirty-check run 18024 var oldValue; 18025 // a shallow copy of the newValue from when the last change happened 18026 var veryOldValue; 18027 // only track veryOldValue if the listener is asking for it 18028 var trackVeryOldValue = (listener.length > 1); 18029 var changeDetected = 0; 18030 var changeDetector = $parse(obj, $watchCollectionInterceptor); 18031 var internalArray = []; 18032 var internalObject = {}; 18033 var initRun = true; 18034 var oldLength = 0; 18035 18036 function $watchCollectionInterceptor(_value) { 18037 newValue = _value; 18038 var newLength, key, bothNaN, newItem, oldItem; 18039 18040 // If the new value is undefined, then return undefined as the watch may be a one-time watch 18041 if (isUndefined(newValue)) return; 18042 18043 if (!isObject(newValue)) { // if primitive 18044 if (oldValue !== newValue) { 18045 oldValue = newValue; 18046 changeDetected++; 18047 } 18048 } else if (isArrayLike(newValue)) { 18049 if (oldValue !== internalArray) { 18050 // we are transitioning from something which was not an array into array. 18051 oldValue = internalArray; 18052 oldLength = oldValue.length = 0; 18053 changeDetected++; 18054 } 18055 18056 newLength = newValue.length; 18057 18058 if (oldLength !== newLength) { 18059 // if lengths do not match we need to trigger change notification 18060 changeDetected++; 18061 oldValue.length = oldLength = newLength; 18062 } 18063 // copy the items to oldValue and look for changes. 18064 for (var i = 0; i < newLength; i++) { 18065 oldItem = oldValue[i]; 18066 newItem = newValue[i]; 18067 18068 // eslint-disable-next-line no-self-compare 18069 bothNaN = (oldItem !== oldItem) && (newItem !== newItem); 18070 if (!bothNaN && (oldItem !== newItem)) { 18071 changeDetected++; 18072 oldValue[i] = newItem; 18073 } 18074 } 18075 } else { 18076 if (oldValue !== internalObject) { 18077 // we are transitioning from something which was not an object into object. 18078 oldValue = internalObject = {}; 18079 oldLength = 0; 18080 changeDetected++; 18081 } 18082 // copy the items to oldValue and look for changes. 18083 newLength = 0; 18084 for (key in newValue) { 18085 if (hasOwnProperty.call(newValue, key)) { 18086 newLength++; 18087 newItem = newValue[key]; 18088 oldItem = oldValue[key]; 18089 18090 if (key in oldValue) { 18091 // eslint-disable-next-line no-self-compare 18092 bothNaN = (oldItem !== oldItem) && (newItem !== newItem); 18093 if (!bothNaN && (oldItem !== newItem)) { 18094 changeDetected++; 18095 oldValue[key] = newItem; 18096 } 18097 } else { 18098 oldLength++; 18099 oldValue[key] = newItem; 18100 changeDetected++; 18101 } 18102 } 18103 } 18104 if (oldLength > newLength) { 18105 // we used to have more keys, need to find them and destroy them. 18106 changeDetected++; 18107 for (key in oldValue) { 18108 if (!hasOwnProperty.call(newValue, key)) { 18109 oldLength--; 18110 delete oldValue[key]; 18111 } 18112 } 18113 } 18114 } 18115 return changeDetected; 18116 } 18117 18118 function $watchCollectionAction() { 18119 if (initRun) { 18120 initRun = false; 18121 listener(newValue, newValue, self); 18122 } else { 18123 listener(newValue, veryOldValue, self); 18124 } 18125 18126 // make a copy for the next time a collection is changed 18127 if (trackVeryOldValue) { 18128 if (!isObject(newValue)) { 18129 //primitive 18130 veryOldValue = newValue; 18131 } else if (isArrayLike(newValue)) { 18132 veryOldValue = new Array(newValue.length); 18133 for (var i = 0; i < newValue.length; i++) { 18134 veryOldValue[i] = newValue[i]; 18135 } 18136 } else { // if object 18137 veryOldValue = {}; 18138 for (var key in newValue) { 18139 if (hasOwnProperty.call(newValue, key)) { 18140 veryOldValue[key] = newValue[key]; 18141 } 18142 } 18143 } 18144 } 18145 } 18146 18147 return this.$watch(changeDetector, $watchCollectionAction); 18148 }, 18149 18150 /** 18151 * @ngdoc method 18152 * @name $rootScope.Scope#$digest 18153 * @kind function 18154 * 18155 * @description 18156 * Processes all of the {@link ng.$rootScope.Scope#$watch watchers} of the current scope and 18157 * its children. Because a {@link ng.$rootScope.Scope#$watch watcher}'s listener can change 18158 * the model, the `$digest()` keeps calling the {@link ng.$rootScope.Scope#$watch watchers} 18159 * until no more listeners are firing. This means that it is possible to get into an infinite 18160 * loop. This function will throw `'Maximum iteration limit exceeded.'` if the number of 18161 * iterations exceeds 10. 18162 * 18163 * Usually, you don't call `$digest()` directly in 18164 * {@link ng.directive:ngController controllers} or in 18165 * {@link ng.$compileProvider#directive directives}. 18166 * Instead, you should call {@link ng.$rootScope.Scope#$apply $apply()} (typically from within 18167 * a {@link ng.$compileProvider#directive directive}), which will force a `$digest()`. 18168 * 18169 * If you want to be notified whenever `$digest()` is called, 18170 * you can register a `watchExpression` function with 18171 * {@link ng.$rootScope.Scope#$watch $watch()} with no `listener`. 18172 * 18173 * In unit tests, you may need to call `$digest()` to simulate the scope life cycle. 18174 * 18175 *
vendor: 9,120 bytes, lines 18175-18398
18175# Example 18176 * ```js 18177 var scope = ...; 18178 scope.name = 'misko'; 18179 scope.counter = 0; 18180 18181 expect(scope.counter).toEqual(0); 18182 scope.$watch('name', function(newValue, oldValue) { 18183 scope.counter = scope.counter + 1; 18184 }); 18185 expect(scope.counter).toEqual(0); 18186 18187 scope.$digest(); 18188 // the listener is always called during the first $digest loop after it was registered 18189 expect(scope.counter).toEqual(1); 18190 18191 scope.$digest(); 18192 // but now it will not be called unless the value changes 18193 expect(scope.counter).toEqual(1); 18194 18195 scope.name = 'adam'; 18196 scope.$digest(); 18197 expect(scope.counter).toEqual(2); 18198 * ``` 18199 * 18200 */ 18201 $digest: function() { 18202 var watch, value, last, fn, get, 18203 watchers, 18204 dirty, ttl = TTL, 18205 next, current, target = this, 18206 watchLog = [], 18207 logIdx, asyncTask; 18208 18209 beginPhase('$digest'); 18210 // Check for changes to browser url that happened in sync before the call to $digest 18211 $browser.$$checkUrlChange(); 18212 18213 if (this === $rootScope && applyAsyncId !== null) { 18214 // If this is the root scope, and $applyAsync has scheduled a deferred $apply(), then 18215 // cancel the scheduled $apply and flush the queue of expressions to be evaluated. 18216 $browser.defer.cancel(applyAsyncId); 18217 flushApplyAsync(); 18218 } 18219 18220 lastDirtyWatch = null; 18221 18222 do { // "while dirty" loop 18223 dirty = false; 18224 current = target; 18225 18226 // It's safe for asyncQueuePosition to be a local variable here because this loop can't 18227 // be reentered recursively. Calling $digest from a function passed to $evalAsync would 18228 // lead to a '$digest already in progress' error. 18229 for (var asyncQueuePosition = 0; asyncQueuePosition < asyncQueue.length; asyncQueuePosition++) { 18230 try { 18231 asyncTask = asyncQueue[asyncQueuePosition]; 18232 fn = asyncTask.fn; 18233 fn(asyncTask.scope, asyncTask.locals); 18234 } catch (e) { 18235 $exceptionHandler(e); 18236 } 18237 lastDirtyWatch = null; 18238 } 18239 asyncQueue.length = 0; 18240 18241 traverseScopesLoop: 18242 do { // "traverse the scopes" loop 18243 if ((watchers = current.$$watchers)) { 18244 // process our watches 18245 watchers.$$digestWatchIndex = watchers.length; 18246 while (watchers.$$digestWatchIndex--) { 18247 try { 18248 watch = watchers[watchers.$$digestWatchIndex]; 18249 // Most common watches are on primitives, in which case we can short 18250 // circuit it with === operator, only when === fails do we use .equals 18251 if (watch) { 18252 get = watch.get; 18253 if ((value = get(current)) !== (last = watch.last) && 18254 !(watch.eq 18255 ? equals(value, last) 18256 : (isNumberNaN(value) && isNumberNaN(last)))) { 18257 dirty = true; 18258 lastDirtyWatch = watch; 18259 watch.last = watch.eq ? copy(value, null) : value; 18260 fn = watch.fn; 18261 fn(value, ((last === initWatchVal) ? value : last), current); 18262 if (ttl < 5) { 18263 logIdx = 4 - ttl; 18264 if (!watchLog[logIdx]) watchLog[logIdx] = []; 18265 watchLog[logIdx].push({ 18266 msg: isFunction(watch.exp) ? 'fn: ' + (watch.exp.name || watch.exp.toString()) : watch.exp, 18267 newVal: value, 18268 oldVal: last 18269 }); 18270 } 18271 } else if (watch === lastDirtyWatch) { 18272 // If the most recently dirty watcher is now clean, short circuit since the remaining watchers 18273 // have already been tested. 18274 dirty = false; 18275 break traverseScopesLoop; 18276 } 18277 } 18278 } catch (e) { 18279 $exceptionHandler(e); 18280 } 18281 } 18282 } 18283 18284 // Insanity Warning: scope depth-first traversal 18285 // yes, this code is a bit crazy, but it works and we have tests to prove it! 18286 // this piece should be kept in sync with the traversal in $broadcast 18287 if (!(next = ((current.$$watchersCount && current.$$childHead) || 18288 (current !== target && current.$$nextSibling)))) { 18289 while (current !== target && !(next = current.$$nextSibling)) { 18290 current = current.$parent; 18291 } 18292 } 18293 } while ((current = next)); 18294 18295 // `break traverseScopesLoop;` takes us to here 18296 18297 if ((dirty || asyncQueue.length) && !(ttl--)) { 18298 clearPhase(); 18299 throw $rootScopeMinErr('infdig', 18300 '{0} $digest() iterations reached. Aborting!\n' + 18301 'Watchers fired in the last 5 iterations: {1}', 18302 TTL, watchLog); 18303 } 18304 18305 } while (dirty || asyncQueue.length); 18306 18307 clearPhase(); 18308 18309 // postDigestQueuePosition isn't local here because this loop can be reentered recursively. 18310 while (postDigestQueuePosition < postDigestQueue.length) { 18311 try { 18312 postDigestQueue[postDigestQueuePosition++](); 18313 } catch (e) { 18314 $exceptionHandler(e); 18315 } 18316 } 18317 postDigestQueue.length = postDigestQueuePosition = 0; 18318 18319 // Check for changes to browser url that happened during the $digest 18320 // (for which no event is fired; e.g. via `history.pushState()`) 18321 $browser.$$checkUrlChange(); 18322 }, 18323 18324 18325 /** 18326 * @ngdoc event 18327 * @name $rootScope.Scope#$destroy 18328 * @eventType broadcast on scope being destroyed 18329 * 18330 * @description 18331 * Broadcasted when a scope and its children are being destroyed. 18332 * 18333 * Note that, in AngularJS, there is also a `$destroy` jQuery event, which can be used to 18334 * clean up DOM bindings before an element is removed from the DOM. 18335 */ 18336 18337 /** 18338 * @ngdoc method 18339 * @name $rootScope.Scope#$destroy 18340 * @kind function 18341 * 18342 * @description 18343 * Removes the current scope (and all of its children) from the parent scope. Removal implies 18344 * that calls to {@link ng.$rootScope.Scope#$digest $digest()} will no longer 18345 * propagate to the current scope and its children. Removal also implies that the current 18346 * scope is eligible for garbage collection. 18347 * 18348 * The `$destroy()` is usually used by directives such as 18349 * {@link ng.directive:ngRepeat ngRepeat} for managing the 18350 * unrolling of the loop. 18351 * 18352 * Just before a scope is destroyed, a `$destroy` event is broadcasted on this scope. 18353 * Application code can register a `$destroy` event handler that will give it a chance to 18354 * perform any necessary cleanup. 18355 * 18356 * Note that, in AngularJS, there is also a `$destroy` jQuery event, which can be used to 18357 * clean up DOM bindings before an element is removed from the DOM. 18358 */ 18359 $destroy: function() { 18360 // We can't destroy a scope that has been already destroyed. 18361 if (this.$$destroyed) return; 18362 var parent = this.$parent; 18363 18364 this.$broadcast('$destroy'); 18365 this.$$destroyed = true; 18366 18367 if (this === $rootScope) { 18368 //Remove handlers attached to window when $rootScope is removed 18369 $browser.$$applicationDestroyed(); 18370 } 18371 18372 incrementWatchersCount(this, -this.$$watchersCount); 18373 for (var eventName in this.$$listenerCount) { 18374 decrementListenerCount(this, this.$$listenerCount[eventName], eventName); 18375 } 18376 18377 // sever all the references to parent scopes (after this cleanup, the current scope should 18378 // not be retained by any of our references and should be eligible for garbage collection) 18379 if (parent && parent.$$childHead === this) parent.$$childHead = this.$$nextSibling; 18380 if (parent && parent.$$childTail === this) parent.$$childTail = this.$$prevSibling; 18381 if (this.$$prevSibling) this.$$prevSibling.$$nextSibling = this.$$nextSibling; 18382 if (this.$$nextSibling) this.$$nextSibling.$$prevSibling = this.$$prevSibling; 18383 18384 // Disable listeners, watchers and apply/digest methods 18385 this.$destroy = this.$digest = this.$apply = this.$evalAsync = this.$applyAsync = noop; 18386 this.$on = this.$watch = this.$watchGroup = function() { return noop; }; 18387 this.$$listeners = {}; 18388 18389 // Disconnect the next sibling to prevent `cleanUpScope` destroying those too 18390 this.$$nextSibling = null; 18391 cleanUpScope(this); 18392 }, 18393 18394 /** 18395 * @ngdoc method 18396 * @name $rootScope.Scope#$eval 18397 * @kind function 18398 *
18399 * @description 18400 * Executes the `expression` on the current scope and returns the result. Any exceptions in 18401 * the expression are propagated (uncaught). This is useful when evaluating Angular 18402 * expressions. 18403 * 18404 * # Example 18405 * ```js 18406 var scope = ng.$rootScope.Scope(); 18407 scope.a = 1; 18408 scope.b = 2; 18409 18410 expect(scope.$eval('a+b')).toEqual(3); 18411 expect(scope.$eval(function(scope){ return scope.a + scope.b; })).toEqual(3); 18412 * ``` 18413 * 18414 * @param {(string|function())=} expression An angular expression to be executed. 18415 * 18416 * - `string`: execute using the rules as defined in {@link guide/expression expression}. 18417 * - `function(scope)`: execute the function with the current `scope` parameter. 18418 * 18419 * @param {(object)=} locals Local variables object, useful for overriding values in scope. 18420 * @returns {*} The result of evaluating the expression. 18421 */ 18422 $eval: function(expr, locals) { 18423 return $parse(expr)(this, locals); 18424 }, 18425 18426 /** 18427 * @ngdoc method 18428 * @name $rootScope.Scope#$evalAsync 18429 * @kind function 18430 * 18431 * @description 18432 * Executes the expression on the current scope at a later point in time. 18433 * 18434 * The `$evalAsync` makes no guarantees as to when the `expression` will be executed, only 18435 * that: 18436 * 18437 * - it will execute after the function that scheduled the evaluation (preferably before DOM 18438 * rendering). 18439 * - at least one {@link ng.$rootScope.Scope#$digest $digest cycle} will be performed after 18440 * `expression` execution. 18441 * 18442 * Any exceptions from the execution of the expression are forwarded to the 18443 * {@link ng.$exceptionHandler $exceptionHandler} service. 18444 * 18445 * __Note:__ if this function is called outside of a `$digest` cycle, a new `$digest` cycle 18446 * will be scheduled. However, it is encouraged to always call code that changes the model 18447 * from within an `$apply` call. That includes code evaluated via `$evalAsync`. 18448 * 18449 * @param {(string|function())=} expression An angular expression to be executed. 18450 * 18451 * - `string`: execute using the rules as defined in {@link guide/expression expression}. 18452 * - `function(scope)`: execute the function with the current `scope` parameter. 18453 * 18454 * @param {(object)=} locals Local variables object, useful for overriding values in scope. 18455 */ 18456 $evalAsync: function(expr, locals) { 18457 // if we are outside of an $digest loop and this is the first time we are scheduling async 18458 // task also schedule async auto-flush 18459 if (!$rootScope.$$phase && !asyncQueue.length) { 18460 $browser.defer(function() { 18461 if (asyncQueue.length) { 18462 $rootScope.$digest(); 18463 } 18464 }); 18465 } 18466 18467 asyncQueue.push({scope: this, fn: $parse(expr), locals: locals}); 18468 }, 18469 18470 $$postDigest: function(fn) { 18471 postDigestQueue.push(fn); 18472 }, 18473 18474 /** 18475 * @ngdoc method 18476 * @name $rootScope.Scope#$apply 18477 * @kind function 18478 * 18479 * @description 18480 * `$apply()` is used to execute an expression in angular from outside of the angular 18481 * framework. (For example from browser DOM events, setTimeout, XHR or third party libraries). 18482 * Because we are calling into the angular framework we need to perform proper scope life 18483 * cycle of {@link ng.$exceptionHandler exception handling}, 18484 * {@link ng.$rootScope.Scope#$digest executing watches}. 18485 * 18486 * ## Life cycle 18487 * 18488 * # Pseudo-Code of `$apply()` 18489 * ```js 18490 function $apply(expr) { 18491 try { 18492 return $eval(expr); 18493 } catch (e) { 18494 $exceptionHandler(e); 18495 } finally { 18496 $root.$digest(); 18497 } 18498 } 18499 * ``` 18500 * 18501 * 18502 * Scope's `$apply()` method transitions through the following stages: 18503 * 18504 * 1. The {@link guide/expression expression} is executed using the 18505 * {@link ng.$rootScope.Scope#$eval $eval()} method. 18506 * 2. Any exceptions from the execution of the expression are forwarded to the 18507 * {@link ng.$exceptionHandler $exceptionHandler} service.
18508 * 3. The {@link ng.$rootScope.Scope#$watch watch} listeners are fired immediately after the 18509 * expression was executed using the {@link ng.$rootScope.Scope#$digest $digest()} method. 18510 * 18511 * 18512 * @param {(string|function())=} exp An angular expression to be executed. 18513 * 18514 * - `string`: execute using the rules as defined in {@link guide/expression expression}. 18515 * - `function(scope)`: execute the function with current `scope` parameter. 18516 * 18517 * @returns {*} The result of evaluating the expression. 18518 */ 18519 $apply: function(expr) { 18520 try { 18521 beginPhase('$apply'); 18522 try { 18523 return this.$eval(expr); 18524 } finally { 18525 clearPhase(); 18526 } 18527 } catch (e) { 18528 $exceptionHandler(e); 18529 } finally { 18530 try { 18531 $rootScope.$digest(); 18532 } catch (e) { 18533 $exceptionHandler(e); 18534 // eslint-disable-next-line no-unsafe-finally 18535 throw e; 18536 } 18537 } 18538 }, 18539 18540 /** 18541 * @ngdoc method 18542 * @name $rootScope.Scope#$applyAsync 18543 * @kind function 18544 * 18545 * @description 18546 * Schedule the invocation of $apply to occur at a later time. The actual time difference 18547 * varies across browsers, but is typically around ~10 milliseconds. 18548 * 18549 * This can be used to queue up multiple expressions which need to be evaluated in the same 18550 * digest. 18551 * 18552 * @param {(string|function())=} exp An angular expression to be executed. 18553 * 18554 * - `string`: execute using the rules as defined in {@link guide/expression expression}. 18555 * - `function(scope)`: execute the function with current `scope` parameter. 18556 */ 18557 $applyAsync: function(expr) { 18558 var scope = this; 18559 if (expr) { 18560 applyAsyncQueue.push($applyAsyncExpression); 18561 } 18562 expr = $parse(expr); 18563 scheduleApplyAsync(); 18564 18565 function $applyAsyncExpression() { 18566 scope.$eval(expr); 18567 } 18568 }, 18569 18570 /** 18571 * @ngdoc method 18572 * @name $rootScope.Scope#$on 18573 * @kind function 18574 * 18575 * @description 18576 * Listens on events of a given type. See {@link ng.$rootScope.Scope#$emit $emit} for 18577 * discussion of event life cycle. 18578 * 18579 * The event listener function format is: `function(event, args...)`. The `event` object 18580 * passed into the listener has the following attributes: 18581 * 18582 * - `targetScope` - `{Scope}`: the scope on which the event was `$emit`-ed or 18583 * `$broadcast`-ed. 18584 * - `currentScope` - `{Scope}`: the scope that is currently handling the event. Once the 18585 * event propagates through the scope hierarchy, this property is set to null. 18586 * - `name` - `{string}`: name of the event. 18587 * - `stopPropagation` - `{function=}`: calling `stopPropagation` function will cancel 18588 * further event propagation (available only for events that were `$emit`-ed). 18589 * - `preventDefault` - `{function}`: calling `preventDefault` sets `defaultPrevented` flag 18590 * to true. 18591 * - `defaultPrevented` - `{boolean}`: true if `preventDefault` was called. 18592 * 18593 * @param {string} name Event name to listen on. 18594 * @param {function(event, ...args)} listener Function to call when the event is emitted. 18595 * @returns {function()} Returns a deregistration function for this listener. 18596 */ 18597 $on: function(name, listener) { 18598 var namedListeners = this.$$listeners[name]; 18599 if (!namedListeners) { 18600 this.$$listeners[name] = namedListeners = []; 18601 } 18602 namedListeners.push(listener); 18603 18604 var current = this; 18605 do { 18606 if (!current.$$listenerCount[name]) { 18607 current.$$listenerCount[name] = 0; 18608 } 18609 current.$$listenerCount[name]++; 18610 } while ((current = current.$parent)); 18611 18612 var self = this; 18613 return function() { 18614 var indexOfListener = namedListeners.indexOf(listener); 18615 if (indexOfListener !== -1) { 18616 namedListeners[indexOfListener] = null; 18617 decrementListenerCount(self, 1, name); 18618 } 18619 }; 18620 }, 18621 18622 18623 /** 18624 * @ngdoc method 18625 * @name $rootScope.Scope#$emit 18626 * @kind function 18627 *
18628 * @description 18629 * Dispatches an event `name` upwards through the scope hierarchy notifying the 18630 * registered {@link ng.$rootScope.Scope#$on} listeners. 18631 * 18632 * The event life cycle starts at the scope on which `$emit` was called. All 18633 * {@link ng.$rootScope.Scope#$on listeners} listening for `name` event on this scope get 18634 * notified. Afterwards, the event traverses upwards toward the root scope and calls all 18635 * registered listeners along the way. The event will stop propagating if one of the listeners 18636 * cancels it. 18637 * 18638 * Any exception emitted from the {@link ng.$rootScope.Scope#$on listeners} will be passed 18639 * onto the {@link ng.$exceptionHandler $exceptionHandler} service. 18640 * 18641 * @param {string} name Event name to emit. 18642 * @param {...*} args Optional one or more arguments which will be passed onto the event listeners. 18643 * @return {Object} Event object (see {@link ng.$rootScope.Scope#$on}). 18644 */ 18645 $emit: function(name, args) { 18646 var empty = [], 18647 namedListeners, 18648 scope = this, 18649 stopPropagation = false, 18650 event = { 18651 name: name, 18652 targetScope: scope, 18653 stopPropagation: function() {stopPropagation = true;}, 18654 preventDefault: function() { 18655 event.defaultPrevented = true; 18656 }, 18657 defaultPrevented: false 18658 }, 18659 listenerArgs = concat([event], arguments, 1), 18660 i, length; 18661 18662 do { 18663 namedListeners = scope.$$listeners[name] || empty; 18664 event.currentScope = scope; 18665 for (i = 0, length = namedListeners.length; i < length; i++) { 18666 18667 // if listeners were deregistered, defragment the array 18668 if (!namedListeners[i]) { 18669 namedListeners.splice(i, 1); 18670 i--; 18671 length--; 18672 continue; 18673 } 18674 try { 18675 //allow all listeners attached to the current scope to run 18676 namedListeners[i].apply(null, listenerArgs); 18677 } catch (e) { 18678 $exceptionHandler(e); 18679 } 18680 } 18681 //if any listener on the current scope stops propagation, prevent bubbling 18682 if (stopPropagation) { 18683 event.currentScope = null; 18684 return event; 18685 } 18686 //traverse upwards 18687 scope = scope.$parent; 18688 } while (scope); 18689 18690 event.currentScope = null; 18691 18692 return event; 18693 }, 18694 18695 18696 /** 18697 * @ngdoc method 18698 * @name $rootScope.Scope#$broadcast 18699 * @kind function 18700 * 18701 * @description 18702 * Dispatches an event `name` downwards to all child scopes (and their children) notifying the 18703 * registered {@link ng.$rootScope.Scope#$on} listeners. 18704 * 18705 * The event life cycle starts at the scope on which `$broadcast` was called. All 18706 * {@link ng.$rootScope.Scope#$on listeners} listening for `name` event on this scope get 18707 * notified. Afterwards, the event propagates to all direct and indirect scopes of the current 18708 * scope and calls all registered listeners along the way. The event cannot be canceled. 18709 * 18710 * Any exception emitted from the {@link ng.$rootScope.Scope#$on listeners} will be passed 18711 * onto the {@link ng.$exceptionHandler $exceptionHandler} service. 18712 * 18713 * @param {string} name Event name to broadcast. 18714 * @param {...*} args Optional one or more arguments which will be passed onto the event listeners. 18715 * @return {Object} Event object, see {@link ng.$rootScope.Scope#$on} 18716 */ 18717 $broadcast: function(name, args) { 18718 var target = this, 18719 current = target, 18720 next = target, 18721 event = { 18722 name: name, 18723 targetScope: target, 18724 preventDefault: function() { 18725 event.defaultPrevented = true; 18726 }, 18727 defaultPrevented: false 18728 }; 18729 18730 if (!target.$$listenerCount[name]) return event; 18731 18732 var listenerArgs = concat([event], arguments, 1), 18733 listeners, i, length; 18734 18735 //down while you can, then up and next sibling or up and next sibling until back at root 18736 while ((current = next)) { 18737 event.currentScope = current; 18738 listeners = current.$$listeners[name] || []; 18739 for (i = 0, length = listeners.length; i < length; i++) { 18740 // if listeners were deregistered, defragment the array 18741 if (!listeners[i]) { 18742 listeners.splice(i, 1); 18743 i--; 18744 length--; 18745 continue; 18746 } 18747 18748 try { 18749 listeners[i].apply(null, listenerArgs); 18750 } catch (e) { 18751 $exceptionHandler(e); 18752 } 18753 } 18754 18755 // Insanity Warning: scope depth-first traversal 18756 // yes, this code is a bit crazy, but it works and we have tests to prove it! 18757 // this piece should be kept in sync with the traversal in $digest 18758 // (though it differs due to having the extra check for $$listenerCount) 18759 if (!(next = ((current.$$listenerCount[name] && current.$$childHead) || 18760 (current !== target && current.$$nextSibling)))) { 18761 while (current !== target && !(next = current.$$nextSibling)) { 18762 current = current.$parent; 18763 } 18764 } 18765 } 18766 18767 event.currentScope = null; 18768 return event; 18769 } 18770 }; 18771 18772 var $rootScope = new Scope(); 18773 18774 //The internal queues. Expose them on the $rootScope for debugging/testing purposes. 18775 var asyncQueue = $rootScope.$$asyncQueue = []; 18776 var postDigestQueue = $rootScope.$$postDigestQueue = []; 18777 var applyAsyncQueue = $rootScope.$$applyAsyncQueue = []; 18778 18779 var postDigestQueuePosition = 0; 18780 18781 return $rootScope; 18782 18783 18784 function beginPhase(phase) { 18785 if ($rootScope.$$phase) { 18786 throw $rootScopeMinErr('inprog', '{0} already in progress', $rootScope.$$phase); 18787 } 18788 18789 $rootScope.$$phase = phase; 18790 } 18791 18792 function clearPhase() { 18793 $rootScope.$$phase = null; 18794 } 18795 18796 function incrementWatchersCount(current, count) { 18797 do { 18798 current.$$watchersCount += count; 18799 } while ((current = current.$parent)); 18800 } 18801 18802 function decrementListenerCount(current, count, name) { 18803 do { 18804 current.$$listenerCount[name] -= count; 18805 18806 if (current.$$listenerCount[name] === 0) { 18807 delete current.$$listenerCount[name]; 18808 } 18809 } while ((current = current.$parent)); 18810 } 18811 18812 /** 18813 * function used as an initial value for watchers. 18814 * because it's unique we can easily tell it apart from other values 18815 */ 18816 function initWatchVal() {} 18817 18818 function flushApplyAsync() {
vendor: 4,475 bytes, lines 18819-18935
18819 while (applyAsyncQueue.length) { 18820 try { 18821 applyAsyncQueue.shift()(); 18822 } catch (e) { 18823 $exceptionHandler(e); 18824 } 18825 } 18826 applyAsyncId = null; 18827 } 18828 18829 function scheduleApplyAsync() { 18830 if (applyAsyncId === null) { 18831 applyAsyncId = $browser.defer(function() { 18832 $rootScope.$apply(flushApplyAsync); 18833 }); 18834 } 18835 } 18836 }]; 18837} 18838 18839/** 18840 * @ngdoc service 18841 * @name $rootElement 18842 * 18843 * @description 18844 * The root element of Angular application. This is either the element where {@link 18845 * ng.directive:ngApp ngApp} was declared or the element passed into 18846 * {@link angular.bootstrap}. The element represents the root element of application. It is also the 18847 * location where the application's {@link auto.$injector $injector} service gets 18848 * published, and can be retrieved using `$rootElement.injector()`. 18849 */ 18850 18851 18852// the implementation is in angular.bootstrap 18853 18854/** 18855 * @this 18856 * @description 18857 * Private service to sanitize uris for links and images. Used by $compile and $sanitize. 18858 */ 18859function $$SanitizeUriProvider() { 18860 var aHrefSanitizationWhitelist = /^\s*(https?|ftp|mailto|tel|file):/, 18861 imgSrcSanitizationWhitelist = /^\s*((https?|ftp|file|blob):|data:image\/)/; 18862 18863 /** 18864 * @description 18865 * Retrieves or overrides the default regular expression that is used for whitelisting of safe 18866 * urls during a[href] sanitization. 18867 * 18868 * The sanitization is a security measure aimed at prevent XSS attacks via html links. 18869 * 18870 * Any url about to be assigned to a[href] via data-binding is first normalized and turned into 18871 * an absolute url. Afterwards, the url is matched against the `aHrefSanitizationWhitelist` 18872 * regular expression. If a match is found, the original url is written into the dom. Otherwise, 18873 * the absolute url is prefixed with `'unsafe:'` string and only then is it written into the DOM. 18874 * 18875 * @param {RegExp=} regexp New regexp to whitelist urls with. 18876 * @returns {RegExp|ng.$compileProvider} Current RegExp if called without value or self for 18877 * chaining otherwise. 18878 */ 18879 this.aHrefSanitizationWhitelist = function(regexp) { 18880 if (isDefined(regexp)) { 18881 aHrefSanitizationWhitelist = regexp; 18882 return this; 18883 } 18884 return aHrefSanitizationWhitelist; 18885 }; 18886 18887 18888 /** 18889 * @description 18890 * Retrieves or overrides the default regular expression that is used for whitelisting of safe 18891 * urls during img[src] sanitization. 18892 * 18893 * The sanitization is a security measure aimed at prevent XSS attacks via html links. 18894 * 18895 * Any url about to be assigned to img[src] via data-binding is first normalized and turned into 18896 * an absolute url. Afterwards, the url is matched against the `imgSrcSanitizationWhitelist` 18897 * regular expression. If a match is found, the original url is written into the dom. Otherwise, 18898 * the absolute url is prefixed with `'unsafe:'` string and only then is it written into the DOM. 18899 * 18900 * @param {RegExp=} regexp New regexp to whitelist urls with. 18901 * @returns {RegExp|ng.$compileProvider} Current RegExp if called without value or self for 18902 * chaining otherwise. 18903 */ 18904 this.imgSrcSanitizationWhitelist = function(regexp) { 18905 if (isDefined(regexp)) { 18906 imgSrcSanitizationWhitelist = regexp; 18907 return this; 18908 } 18909 return imgSrcSanitizationWhitelist; 18910 }; 18911 18912 this.$get = function() { 18913 return function sanitizeUri(uri, isImage) { 18914 var regex = isImage ? imgSrcSanitizationWhitelist : aHrefSanitizationWhitelist; 18915 var normalizedVal; 18916 normalizedVal = urlResolve(uri).href; 18917 if (normalizedVal !== '' && !normalizedVal.match(regex)) { 18918 return 'unsafe:' + normalizedVal; 18919 } 18920 return uri; 18921 }; 18922 }; 18923} 18924 18925/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * 18926 * Any commits to this file should be reviewed with security in mind. * 18927 * Changes to this file can potentially create security vulnerabilities. * 18928 * An approval from 2 Core members with history of modifying * 18929 * this file is required. * 18930 * * 18931 * Does the change somehow allow for arbitrary javascript to be executed? * 18932 * Or allows for someone to change the prototype of built-in objects? * 18933 * Or gives undesired access to variables likes document or window? * 18934 * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ 18935
18936/* exported $SceProvider, $SceDelegateProvider */ 18937 18938var $sceMinErr = minErr('$sce'); 18939 18940var SCE_CONTEXTS = { 18941 // HTML is used when there's HTML rendered (e.g. ng-bind-html, iframe srcdoc binding). 18942 HTML: 'html', 18943 18944 // Style statements or stylesheets. Currently unused in AngularJS. 18945 CSS: 'css', 18946 18947 // An URL used in a context where it does not refer to a resource that loads code. Currently 18948 // unused in AngularJS. 18949 URL: 'url', 18950 18951 // RESOURCE_URL is a subtype of URL used where the referred-to resource could be interpreted as 18952 // code. (e.g. ng-include, script src binding, templateUrl) 18953 RESOURCE_URL: 'resourceUrl', 18954 18955 // Script. Currently unused in AngularJS. 18956 JS: 'js' 18957}; 18958 18959// Helper functions follow. 18960 18961var UNDERSCORE_LOWERCASE_REGEXP = /_([a-z])/g; 18962 18963function snakeToCamel(name) { 18964 return name 18965 .replace(UNDERSCORE_LOWERCASE_REGEXP, fnCamelCaseReplace); 18966} 18967 18968function adjustMatcher(matcher) { 18969 if (matcher === 'self') { 18970 return matcher; 18971 } else if (isString(matcher)) { 18972 // Strings match exactly except for 2 wildcards - '*' and '**'. 18973 // '*' matches any character except those from the set ':/.?&'. 18974 // '**' matches any character (like .* in a RegExp). 18975 // More than 2 *'s raises an error as it's ill defined. 18976 if (matcher.indexOf('***') > -1) { 18977 throw $sceMinErr('iwcard', 18978 'Illegal sequence *** in string matcher. String: {0}', matcher); 18979 } 18980 matcher = escapeForRegexp(matcher).
18981 replace(/\\\*\\\*/g, '.*'). 18982 replace(/\\\*/g, '[^:/.?&;]*'); 18983 return new RegExp('^' + matcher + '$'); 18984 } else if (isRegExp(matcher)) { 18985 // The only other type of matcher allowed is a Regexp. 18986 // Match entire URL / disallow partial matches. 18987 // Flags are reset (i.e. no global, ignoreCase or multiline) 18988 return new RegExp('^' + matcher.source + '$'); 18989 } else { 18990 throw $sceMinErr('imatcher', 18991 'Matchers may only be "self", string patterns or RegExp objects'); 18992 } 18993} 18994 18995 18996function adjustMatchers(matchers) { 18997 var adjustedMatchers = []; 18998 if (isDefined(matchers)) { 18999 forEach(matchers, function(matcher) { 19000 adjustedMatchers.push(adjustMatcher(matcher)); 19001 }); 19002 } 19003 return adjustedMatchers; 19004} 19005 19006 19007/** 19008 * @ngdoc service 19009 * @name $sceDelegate 19010 * @kind function 19011 * 19012 * @description 19013 * 19014 * `$sceDelegate` is a service that is used by the `$sce` service to provide {@link ng.$sce Strict 19015 * Contextual Escaping (SCE)} services to AngularJS. 19016 * 19017 * For an overview of this service and the functionnality it provides in AngularJS, see the main 19018 * page for {@link ng.$sce SCE}. The current page is targeted for developers who need to alter how 19019 * SCE works in their application, which shouldn't be needed in most cases. 19020 * 19021 * <div class="alert alert-danger"> 19022 * AngularJS strongly relies on contextual escaping for the security of bindings: disabling or 19023 * modifying this might cause cross site scripting (XSS) vulnerabilities. For libraries owners, 19024 * changes to this service will also influence users, so be extra careful and document your changes. 19025 * </div> 19026 * 19027 * Typically, you would configure or override the {@link ng.$sceDelegate $sceDelegate} instead of 19028 * the `$sce` service to customize the way Strict Contextual Escaping works in AngularJS. This is 19029 * because, while the `$sce` provides numerous shorthand methods, etc., you really only need to 19030 * override 3 core functions (`trustAs`, `getTrusted` and `valueOf`) to replace the way things 19031 * work because `$sce` delegates to `$sceDelegate` for these operations. 19032 * 19033 * Refer {@link ng.$sceDelegateProvider $sceDelegateProvider} to configure this service. 19034 * 19035 * The default instance of `$sceDelegate` should work out of the box with little pain. While you 19036 * can override it completely to change the behavior of `$sce`, the common case would 19037 * involve configuring the {@link ng.$sceDelegateProvider $sceDelegateProvider} instead by setting 19038 * your own whitelists and blacklists for trusting URLs used for loading AngularJS resources such as 19039 * templates. Refer {@link ng.$sceDelegateProvider#resourceUrlWhitelist 19040 * $sceDelegateProvider.resourceUrlWhitelist} and {@link 19041 * ng.$sceDelegateProvider#resourceUrlBlacklist $sceDelegateProvider.resourceUrlBlacklist} 19042 */ 19043 19044/** 19045 * @ngdoc provider 19046 * @name $sceDelegateProvider 19047 * @this 19048 * 19049 * @description 19050 * 19051 * The `$sceDelegateProvider` provider allows developers to configure the {@link ng.$sceDelegate 19052 * $sceDelegate service}, used as a delegate for {@link ng.$sce Strict Contextual Escaping (SCE)}. 19053 * 19054 * The `$sceDelegateProvider` allows one to get/set the whitelists and blacklists used to ensure 19055 * that the URLs used for sourcing AngularJS templates and other script-running URLs are safe (all 19056 * places that use the `$sce.RESOURCE_URL` context). See 19057 * {@link ng.$sceDelegateProvider#resourceUrlWhitelist $sceDelegateProvider.resourceUrlWhitelist} 19058 * and 19059 * {@link ng.$sceDelegateProvider#resourceUrlBlacklist $sceDelegateProvider.resourceUrlBlacklist}, 19060 * 19061 * For the general details about this service in Angular, read the main page for {@link ng.$sce 19062 * Strict Contextual Escaping (SCE)}. 19063 * 19064 * **Example**: Consider the following case. <a name="example"></a> 19065 * 19066 * - your app is hosted at url `http://myapp.example.com/` 19067 * - but some of your templates are hosted on other domains you control such as 19068 * `http://srv01.assets.example.com/`, `http://srv02.assets.example.com/`, etc. 19069 * - and you have an open redirect at `http://myapp.example.com/clickThru?...`. 19070 * 19071 * Here is what a secure configuration for this scenario might look like: 19072 * 19073 * ``` 19074 * angular.module('myApp', []).config(function($sceDelegateProvider) { 19075 * $sceDelegateProvider.resourceUrlWhitelist([ 19076 * // Allow same origin resource loads. 19077 * 'self', 19078 * // Allow loading from our assets domain. Notice the difference between * and **. 19079 * 'http://srv*.assets.example.com/**' 19080 * ]); 19081 *
19082 * // The blacklist overrides the whitelist so the open redirect here is blocked. 19083 * $sceDelegateProvider.resourceUrlBlacklist([ 19084 * 'http://myapp.example.com/clickThru**' 19085 * ]); 19086 * }); 19087 * ``` 19088 * Note that an empty whitelist will block every resource URL from being loaded, and will require 19089 * you to manually mark each one as trusted with `$sce.trustAsResourceUrl`. However, templates 19090 * requested by {@link ng.$templateRequest $templateRequest} that are present in 19091 * {@link ng.$templateCache $templateCache} will not go through this check. If you have a mechanism 19092 * to populate your templates in that cache at config time, then it is a good idea to remove 'self' 19093 * from that whitelist. This helps to mitigate the security impact of certain types of issues, like 19094 * for instance attacker-controlled `ng-includes`. 19095 */ 19096 19097function $SceDelegateProvider() { 19098 this.SCE_CONTEXTS = SCE_CONTEXTS; 19099 19100 // Resource URLs can also be trusted by policy. 19101 var resourceUrlWhitelist = ['self'], 19102 resourceUrlBlacklist = []; 19103 19104 /** 19105 * @ngdoc method 19106 * @name $sceDelegateProvider#resourceUrlWhitelist 19107 * @kind function 19108 * 19109 * @param {Array=} whitelist When provided, replaces the resourceUrlWhitelist with the value 19110 * provided. This must be an array or null. A snapshot of this array is used so further 19111 * changes to the array are ignored. 19112 * Follow {@link ng.$sce#resourceUrlPatternItem this link} for a description of the items 19113 * allowed in this array. 19114 * 19115 * @return {Array} The currently set whitelist array. 19116 * 19117 * @description 19118 * Sets/Gets the whitelist of trusted resource URLs. 19119 * 19120 * The **default value** when no whitelist has been explicitly set is `['self']` allowing only 19121 * same origin resource requests. 19122 * 19123 * <div class="alert alert-warning"> 19124 * **Note:** the default whitelist of 'self' is not recommended if your app shares its origin 19125 * with other apps! It is a good idea to limit it to only your application's directory. 19126 * </div> 19127 */ 19128 this.resourceUrlWhitelist = function(value) { 19129 if (arguments.length) { 19130 resourceUrlWhitelist = adjustMatchers(value); 19131 } 19132 return resourceUrlWhitelist; 19133 }; 19134 19135 /** 19136 * @ngdoc method 19137 * @name $sceDelegateProvider#resourceUrlBlacklist 19138 * @kind function 19139 * 19140 * @param {Array=} blacklist When provided, replaces the resourceUrlBlacklist with the value 19141 * provided. This must be an array or null. A snapshot of this array is used so further 19142 * changes to the array are ignored.</p><p> 19143 * Follow {@link ng.$sce#resourceUrlPatternItem this link} for a description of the items 19144 * allowed in this array.</p><p> 19145 * The typical usage for the blacklist is to **block 19146 * [open redirects](http://cwe.mitre.org/data/definitions/601.html)** served by your domain as 19147 * these would otherwise be trusted but actually return content from the redirected domain. 19148 * </p><p> 19149 * Finally, **the blacklist overrides the whitelist** and has the final say. 19150 * 19151 * @return {Array} The currently set blacklist array. 19152 * 19153 * @description 19154 * Sets/Gets the blacklist of trusted resource URLs. 19155 * 19156 * The **default value** when no whitelist has been explicitly set is the empty array (i.e. there 19157 * is no blacklist.) 19158 */ 19159 19160 this.resourceUrlBlacklist = function(value) { 19161 if (arguments.length) { 19162 resourceUrlBlacklist = adjustMatchers(value); 19163 } 19164 return resourceUrlBlacklist; 19165 }; 19166 19167 this.$get = ['$injector', function($injector) { 19168 19169 var htmlSanitizer = function htmlSanitizer(html) { 19170 throw $sceMinErr('unsafe', 'Attempting to use an unsafe value in a safe context.'); 19171 }; 19172 19173 if ($injector.has('$sanitize')) { 19174 htmlSanitizer = $injector.get('$sanitize'); 19175 } 19176 19177 19178 function matchUrl(matcher, parsedUrl) { 19179 if (matcher === 'self') { 19180 return urlIsSameOrigin(parsedUrl); 19181 } else { 19182 // definitely a regex. See adjustMatchers() 19183 return !!matcher.exec(parsedUrl.href); 19184 } 19185 } 19186 19187 function isResourceUrlAllowedByPolicy(url) { 19188 var parsedUrl = urlResolve(url.toString()); 19189 var i, n, allowed = false;
vendor: 4,940 bytes, lines 19190-19309
19190 // Ensure that at least one item from the whitelist allows this url. 19191 for (i = 0, n = resourceUrlWhitelist.length; i < n; i++) { 19192 if (matchUrl(resourceUrlWhitelist[i], parsedUrl)) { 19193 allowed = true; 19194 break; 19195 } 19196 } 19197 if (allowed) { 19198 // Ensure that no item from the blacklist blocked this url. 19199 for (i = 0, n = resourceUrlBlacklist.length; i < n; i++) { 19200 if (matchUrl(resourceUrlBlacklist[i], parsedUrl)) { 19201 allowed = false; 19202 break; 19203 } 19204 } 19205 } 19206 return allowed; 19207 } 19208 19209 function generateHolderType(Base) { 19210 var holderType = function TrustedValueHolderType(trustedValue) { 19211 this.$$unwrapTrustedValue = function() { 19212 return trustedValue; 19213 }; 19214 }; 19215 if (Base) { 19216 holderType.prototype = new Base(); 19217 } 19218 holderType.prototype.valueOf = function sceValueOf() { 19219 return this.$$unwrapTrustedValue(); 19220 }; 19221 holderType.prototype.toString = function sceToString() { 19222 return this.$$unwrapTrustedValue().toString(); 19223 }; 19224 return holderType; 19225 } 19226 19227 var trustedValueHolderBase = generateHolderType(), 19228 byType = {}; 19229 19230 byType[SCE_CONTEXTS.HTML] = generateHolderType(trustedValueHolderBase); 19231 byType[SCE_CONTEXTS.CSS] = generateHolderType(trustedValueHolderBase); 19232 byType[SCE_CONTEXTS.URL] = generateHolderType(trustedValueHolderBase); 19233 byType[SCE_CONTEXTS.JS] = generateHolderType(trustedValueHolderBase); 19234 byType[SCE_CONTEXTS.RESOURCE_URL] = generateHolderType(byType[SCE_CONTEXTS.URL]); 19235 19236 /** 19237 * @ngdoc method 19238 * @name $sceDelegate#trustAs 19239 * 19240 * @description 19241 * Returns a trusted representation of the parameter for the specified context. This trusted 19242 * object will later on be used as-is, without any security check, by bindings or directives 19243 * that require this security context. 19244 * For instance, marking a string as trusted for the `$sce.HTML` context will entirely bypass 19245 * the potential `$sanitize` call in corresponding `$sce.HTML` bindings or directives, such as 19246 * `ng-bind-html`. Note that in most cases you won't need to call this function: if you have the 19247 * sanitizer loaded, passing the value itself will render all the HTML that does not pose a 19248 * security risk. 19249 * 19250 * See {@link ng.$sceDelegate#getTrusted getTrusted} for the function that will consume those 19251 * trusted values, and {@link ng.$sce $sce} for general documentation about strict contextual 19252 * escaping. 19253 * 19254 * @param {string} type The context in which this value is safe for use, e.g. `$sce.URL`, 19255 * `$sce.RESOURCE_URL`, `$sce.HTML`, `$sce.JS` or `$sce.CSS`. 19256 * 19257 * @param {*} value The value that should be considered trusted. 19258 * @return {*} A trusted representation of value, that can be used in the given context. 19259 */ 19260 function trustAs(type, trustedValue) { 19261 var Constructor = (byType.hasOwnProperty(type) ? byType[type] : null); 19262 if (!Constructor) { 19263 throw $sceMinErr('icontext', 19264 'Attempted to trust a value in invalid context. Context: {0}; Value: {1}', 19265 type, trustedValue); 19266 } 19267 if (trustedValue === null || isUndefined(trustedValue) || trustedValue === '') { 19268 return trustedValue; 19269 } 19270 // All the current contexts in SCE_CONTEXTS happen to be strings. In order to avoid trusting 19271 // mutable objects, we ensure here that the value passed in is actually a string. 19272 if (typeof trustedValue !== 'string') { 19273 throw $sceMinErr('itype', 19274 'Attempted to trust a non-string value in a content requiring a string: Context: {0}', 19275 type); 19276 } 19277 return new Constructor(trustedValue); 19278 } 19279 19280 /** 19281 * @ngdoc method 19282 * @name $sceDelegate#valueOf 19283 * 19284 * @description 19285 * If the passed parameter had been returned by a prior call to {@link ng.$sceDelegate#trustAs 19286 * `$sceDelegate.trustAs`}, returns the value that had been passed to {@link 19287 * ng.$sceDelegate#trustAs `$sceDelegate.trustAs`}. 19288 * 19289 * If the passed parameter is not a value that had been returned by {@link 19290 * ng.$sceDelegate#trustAs `$sceDelegate.trustAs`}, it must be returned as-is. 19291 * 19292 * @param {*} value The result of a prior {@link ng.$sceDelegate#trustAs `$sceDelegate.trustAs`} 19293 * call or anything else. 19294 * @return {*} The `value` that was originally provided to {@link ng.$sceDelegate#trustAs 19295 * `$sceDelegate.trustAs`} if `value` is the result of such a call. Otherwise, returns 19296 * `value` unchanged. 19297 */ 19298 function valueOf(maybeTrusted) { 19299 if (maybeTrusted instanceof trustedValueHolderBase) { 19300 return maybeTrusted.$$unwrapTrustedValue(); 19301 } else { 19302 return maybeTrusted; 19303 } 19304 } 19305 19306 /** 19307 * @ngdoc method 19308 * @name $sceDelegate#getTrusted 19309 *
19310 * @description 19311 * Takes any input, and either returns a value that's safe to use in the specified context, or 19312 * throws an exception. 19313 * 19314 * In practice, there are several cases. When given a string, this function runs checks 19315 * and sanitization to make it safe without prior assumptions. When given the result of a {@link 19316 * ng.$sceDelegate#trustAs `$sceDelegate.trustAs`} call, it returns the originally supplied 19317 * value if that value's context is valid for this call's context. Finally, this function can 19318 * also throw when there is no way to turn `maybeTrusted` in a safe value (e.g., no sanitization 19319 * is available or possible.) 19320 * 19321 * @param {string} type The context in which this value is to be used (such as `$sce.HTML`). 19322 * @param {*} maybeTrusted The result of a prior {@link ng.$sceDelegate#trustAs 19323 * `$sceDelegate.trustAs`} call, or anything else (which will not be considered trusted.) 19324 * @return {*} A version of the value that's safe to use in the given context, or throws an 19325 * exception if this is impossible. 19326 */ 19327 function getTrusted(type, maybeTrusted) { 19328 if (maybeTrusted === null || isUndefined(maybeTrusted) || maybeTrusted === '') { 19329 return maybeTrusted; 19330 } 19331 var constructor = (byType.hasOwnProperty(type) ? byType[type] : null); 19332 // If maybeTrusted is a trusted class instance or subclass instance, then unwrap and return 19333 // as-is. 19334 if (constructor && maybeTrusted instanceof constructor) { 19335 return maybeTrusted.$$unwrapTrustedValue(); 19336 } 19337 // Otherwise, if we get here, then we may either make it safe, or throw an exception. This 19338 // depends on the context: some are sanitizatible (HTML), some use whitelists (RESOURCE_URL), 19339 // some are impossible to do (JS). This step isn't implemented for CSS and URL, as AngularJS 19340 // has no corresponding sinks. 19341 if (type === SCE_CONTEXTS.RESOURCE_URL) { 19342 // RESOURCE_URL uses a whitelist. 19343 if (isResourceUrlAllowedByPolicy(maybeTrusted)) { 19344 return maybeTrusted; 19345 } else { 19346 throw $sceMinErr('insecurl', 19347 'Blocked loading resource from url not allowed by $sceDelegate policy. URL: {0}', 19348 maybeTrusted.toString()); 19349 } 19350 } else if (type === SCE_CONTEXTS.HTML) { 19351 // htmlSanitizer throws its own error when no sanitizer is available. 19352 return htmlSanitizer(maybeTrusted); 19353 } 19354 // Default error when the $sce service has no way to make the input safe. 19355 throw $sceMinErr('unsafe', 'Attempting to use an unsafe value in a safe context.'); 19356 } 19357 19358 return { trustAs: trustAs, 19359 getTrusted: getTrusted, 19360 valueOf: valueOf }; 19361 }]; 19362} 19363 19364 19365/** 19366 * @ngdoc provider 19367 * @name $sceProvider 19368 * @this 19369 * 19370 * @description 19371 * 19372 * The $sceProvider provider allows developers to configure the {@link ng.$sce $sce} service. 19373 * - enable/disable Strict Contextual Escaping (SCE) in a module 19374 * - override the default implementation with a custom delegate 19375 * 19376 * Read more about {@link ng.$sce Strict Contextual Escaping (SCE)}. 19377 */ 19378 19379/** 19380 * @ngdoc service 19381 * @name $sce 19382 * @kind function 19383 * 19384 * @description 19385 * 19386 * `$sce` is a service that provides Strict Contextual Escaping services to AngularJS. 19387 * 19388 * # Strict Contextual Escaping 19389 * 19390 * Strict Contextual Escaping (SCE) is a mode in which AngularJS constrains bindings to only render 19391 * trusted values. Its goal is to assist in writing code in a way that (a) is secure by default, and 19392 * (b) makes auditing for security vulnerabilities such as XSS, clickjacking, etc. a lot easier. 19393 * 19394 * ## Overview 19395 * 19396 * To systematically block XSS security bugs, AngularJS treats all values as untrusted by default in 19397 * HTML or sensitive URL bindings. When binding untrusted values, AngularJS will automatically 19398 * run security checks on them (sanitizations, whitelists, depending on context), or throw when it 19399 * cannot guarantee the security of the result. That behavior depends strongly on contexts: HTML 19400 * can be sanitized, but template URLs cannot, for instance. 19401 * 19402 * To illustrate this, consider the `ng-bind-html` directive. It renders its value directly as HTML: 19403 * we call that the *context*. When given an untrusted input, AngularJS will attempt to sanitize it 19404 * before rendering if a sanitizer is available, and throw otherwise. To bypass sanitization and 19405 * render the input as-is, you will need to mark it as trusted for that context before attempting 19406 * to bind it. 19407 * 19408 * As of version 1.2, AngularJS ships with SCE enabled by default. 19409 * 19410 *
vendor: 2,223 bytes, lines 19410-19447
19410## In practice 19411 * 19412 * Here's an example of a binding in a privileged context: 19413 * 19414 * ``` 19415 * <input ng-model="userHtml" aria-label="User input"> 19416 * <div ng-bind-html="userHtml"></div> 19417 * ``` 19418 * 19419 * Notice that `ng-bind-html` is bound to `userHtml` controlled by the user. With SCE 19420 * disabled, this application allows the user to render arbitrary HTML into the DIV, which would 19421 * be an XSS security bug. In a more realistic example, one may be rendering user comments, blog 19422 * articles, etc. via bindings. (HTML is just one example of a context where rendering user 19423 * controlled input creates security vulnerabilities.) 19424 * 19425 * For the case of HTML, you might use a library, either on the client side, or on the server side, 19426 * to sanitize unsafe HTML before binding to the value and rendering it in the document. 19427 * 19428 * How would you ensure that every place that used these types of bindings was bound to a value that 19429 * was sanitized by your library (or returned as safe for rendering by your server?) How can you 19430 * ensure that you didn't accidentally delete the line that sanitized the value, or renamed some 19431 * properties/fields and forgot to update the binding to the sanitized value? 19432 * 19433 * To be secure by default, AngularJS makes sure bindings go through that sanitization, or 19434 * any similar validation process, unless there's a good reason to trust the given value in this 19435 * context. That trust is formalized with a function call. This means that as a developer, you 19436 * can assume all untrusted bindings are safe. Then, to audit your code for binding security issues, 19437 * you just need to ensure the values you mark as trusted indeed are safe - because they were 19438 * received from your server, sanitized by your library, etc. You can organize your codebase to 19439 * help with this - perhaps allowing only the files in a specific directory to do this. 19440 * Ensuring that the internal API exposed by that code doesn't markup arbitrary values as safe then 19441 * becomes a more manageable task. 19442 * 19443 * In the case of AngularJS' SCE service, one uses {@link ng.$sce#trustAs $sce.trustAs} 19444 * (and shorthand methods such as {@link ng.$sce#trustAsHtml $sce.trustAsHtml}, etc.) to 19445 * build the trusted versions of your values. 19446 * 19447 * ##
19447 How does it work? 19448 * 19449 * In privileged contexts, directives and code will bind to the result of {@link ng.$sce#getTrusted 19450 * $sce.getTrusted(context, value)} rather than to the value directly. Think of this function as 19451 * a way to enforce the required security context in your data sink. Directives use {@link 19452 * ng.$sce#parseAs $sce.parseAs} rather than `$parse` to watch attribute bindings, which performs 19453 * the {@link ng.$sce#getTrusted $sce.getTrusted} behind the scenes on non-constant literals. Also, 19454 * when binding without directives, AngularJS will understand the context of your bindings 19455 * automatically. 19456 * 19457 * As an example, {@link ng.directive:ngBindHtml ngBindHtml} uses {@link 19458 * ng.$sce#parseAsHtml $sce.parseAsHtml(binding expression)}. Here's the actual code (slightly 19459 * simplified): 19460 * 19461 * ``` 19462 * var ngBindHtmlDirective = ['$sce', function($sce) { 19463 * return function(scope, element, attr) { 19464 * scope.$watch($sce.parseAsHtml(attr.ngBindHtml), function(value) { 19465 * element.html(value || ''); 19466 * }); 19467 * }; 19468 * }]; 19469 * ``` 19470 * 19471 * ## Impact on loading templates 19472 * 19473 * This applies both to the {@link ng.directive:ngInclude `ng-include`} directive as well as 19474 * `templateUrl`'s specified by {@link guide/directive directives}. 19475 * 19476 * By default, Angular only loads templates from the same domain and protocol as the application 19477 * document. This is done by calling {@link ng.$sce#getTrustedResourceUrl 19478 * $sce.getTrustedResourceUrl} on the template URL. To load templates from other domains and/or 19479 * protocols, you may either {@link ng.$sceDelegateProvider#resourceUrlWhitelist whitelist 19480 * them} or {@link ng.$sce#trustAsResourceUrl wrap it} into a trusted value. 19481 * 19482 * *Please note*: 19483 * The browser's 19484 * [Same Origin Policy](https://code.google.com/p/browsersec/wiki/Part2#Same-origin_policy_for_XMLHttpRequest) 19485 * and [Cross-Origin Resource Sharing (CORS)](http://www.w3.org/TR/cors/) 19486 * policy apply in addition to this and may further restrict whether the template is successfully 19487 * loaded. This means that without the right CORS policy, loading templates from a different domain 19488 * won't work on all browsers. Also, loading templates from `file://` URL does not work on some 19489 * browsers. 19490 * 19491 * ## This feels like too much overhead 19492 * 19493 * It's important to remember that SCE only applies to interpolation expressions. 19494 * 19495 * If your expressions are constant literals, they're automatically trusted and you don't need to 19496 * call `$sce.trustAs` on them (e.g. 19497 * `<div ng-bind-html="'<b>implicitly trusted</b>'"></div>`) just works. The `$sceDelegate` will 19498 * also use the `$sanitize` service if it is available when binding untrusted values to 19499 * `$sce.HTML` context. AngularJS provides an implementation in `angular-sanitize.js`, and if you 19500 * wish to use it, you will also need to depend on the {@link ngSanitize `ngSanitize`} module in 19501 * your application. 19502 * 19503 * The included {@link ng.$sceDelegate $sceDelegate} comes with sane defaults to allow you to load 19504 * templates in `ng-include` from your application's domain without having to even know about SCE. 19505 * It blocks loading templates from other domains or loading templates over http from an https 19506 * served document. You can change these by setting your own custom {@link 19507 * ng.$sceDelegateProvider#resourceUrlWhitelist whitelists} and {@link 19508 * ng.$sceDelegateProvider#resourceUrlBlacklist blacklists} for matching such URLs. 19509 * 19510 * This significantly reduces the overhead. It is far easier to pay the small overhead and have an 19511 * application that's secure and can be audited to verify that with much more ease than bolting 19512 * security onto an application later. 19513 * 19514 * <a name="contexts"></a> 19515 * ## What trusted context types are supported? 19516 * 19517 * | Context | Notes | 19518 * |---------------------|----------------| 19519 * | `$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 $sanitize} service is available (implemented by the {@link ngSanitize ngSanitize} module) this will sanitize the value instead of throwing an error. | 19520 * | `$sce.CSS` | For CSS that's safe to source into the application. Currently, no bindings require this context. Feel free to use it in your own directives. | 19521 * | `$sce.URL` | For URLs that are safe to follow as links. Currently unused (`<a href=`, `<img src=`, and some others sanitize their urls and don't constitute an SCE context.) | 19522 * | `$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`, `VIDEO`, `AUDIO`, `SOURCE`, and `TRACK` (e.g. `IFRAME`, `OBJECT`, etc.) <br><br>Note that `$sce.RESOURCE_URL` makes a stronger statement about the URL than `$sce.URL` does (it's not just the URL that matters, but also what is at the end of it), and therefore contexts requiring values trusted for `$sce.RESOURCE_URL` can be used anywhere that values trusted for `$sce.URL` are required. | 19523 * | `$sce.JS` | For JavaScript that is safe to execute in your application's context. Currently, no bindings require this context. Feel free to use it in your own directives. | 19524 * 19525 * 19526 * Be aware that `a[href]` and `img[src]` automatically sanitize their URLs and do not pass them 19527 * through {@link ng.$sce#getTrusted $sce.getTrusted}. There's no CSS-, URL-, or JS-context bindings 19528 * in AngularJS currently, so their corresponding `$sce.trustAs` functions aren't useful yet. This 19529 * might evolve. 19530 * 19531 * ## Format of items in {@link ng.$sceDelegateProvider#resourceUrlWhitelist resourceUrlWhitelist}/{@link ng.$sceDelegateProvider#resourceUrlBlacklist Blacklist} <a name="resourceUrlPatternItem"></a> 19532 *
19533 * Each element in these arrays must be one of the following: 19534 * 19535 * - **'self'** 19536 * - The special **string**, `'self'`, can be used to match against all URLs of the **same 19537 * domain** as the application document using the **same protocol**. 19538 * - **String** (except the special value `'self'`) 19539 * - The string is matched against the full *normalized / absolute URL* of the resource 19540 * being tested (substring matches are not good enough.) 19541 * - There are exactly **two wildcard sequences** - `*` and `**`. All other characters 19542 * match themselves. 19543 * - `*`: matches zero or more occurrences of any character other than one of the following 6 19544 * characters: '`:`', '`/`', '`.`', '`?`', '`&`' and '`;`'. It's a useful wildcard for use 19545 * in a whitelist. 19546 * - `**`: matches zero or more occurrences of *any* character. As such, it's not 19547 * appropriate for use in a scheme, domain, etc. as it would match too much. (e.g. 19548 * http://**.example.com/ would match http://evil.com/?ignore=.example.com/ and that might 19549 * not have been the intention.) Its usage at the very end of the path is ok. (e.g. 19550 * http://foo.example.com/templates/**). 19551 * - **RegExp** (*see caveat below*) 19552 * - *Caveat*: While regular expressions are powerful and offer great flexibility, their syntax 19553 * (and all the inevitable escaping) makes them *harder to maintain*. It's easy to 19554 * accidentally introduce a bug when one updates a complex expression (imho, all regexes should 19555 * have good test coverage). For instance, the use of `.` in the regex is correct only in a 19556 * small number of cases. A `.` character in the regex used when matching the scheme or a 19557 * subdomain could be matched against a `:` or literal `.` that was likely not intended. It 19558 * is highly recommended to use the string patterns and only fall back to regular expressions 19559 * as a last resort. 19560 * - The regular expression must be an instance of RegExp (i.e. not a string.) It is 19561 * matched against the **entire** *normalized / absolute URL* of the resource being tested 19562 * (even when the RegExp did not have the `^` and `$` codes.) In addition, any flags 19563 * present on the RegExp (such as multiline, global, ignoreCase) are ignored. 19564 * - If you are generating your JavaScript from some other templating engine (not 19565 * recommended, e.g. in issue [#4006](https://github.com/angular/angular.js/issues/4006)), 19566 * remember to escape your regular expression (and be aware that you might need more than 19567 * one level of escaping depending on your templating engine and the way you interpolated 19568 * the value.) Do make use of your platform's escaping mechanism as it might be good 19569 * enough before coding your own. E.g. Ruby has 19570 * [Regexp.escape(str)](http://www.ruby-doc.org/core-2.0.0/Regexp.html#method-c-escape) 19571 * and Python has [re.escape](http://docs.python.org/library/re.html#re.escape). 19572 * Javascript lacks a similar built in function for escaping. Take a look at Google 19573 * Closure library's [goog.string.regExpEscape(s)]( 19574 * http://docs.closure-library.googlecode.com/git/closure_goog_string_string.js.source.html#line962). 19575 * 19576 * Refer {@link ng.$sceDelegateProvider $sceDelegateProvider} for an example. 19577 * 19578 * ## Show me an example using SCE. 19579 * 19580 * <example module="mySceApp" deps="angular-sanitize.js" name="sce-service"> 19581 * <file name="index.html"> 19582 * <div ng-controller="AppController as myCtrl"> 19583 * <i ng-bind-html="myCtrl.explicitlyTrustedHtml" id="explicitlyTrustedHtml"></i><br><br> 19584 * <b>User comments</b><br> 19585 * By default, HTML that isn't explicitly trusted (e.g. Alice's comment) is sanitized when 19586 * $sanitize is available. If $sanitize isn't available, this results in an error instead of an 19587 * exploit. 19588 * <div class="well"> 19589 * <div ng-repeat="userComment in myCtrl.userComments"> 19590 * <b>{{userComment.name}}</b>: 19591 * <span ng-bind-html="userComment.htmlComment" class="htmlComment"></span> 19592 * <br> 19593 * </div>
19594 * </div> 19595 * </div> 19596 * </file> 19597 * 19598 * <file name="script.js"> 19599 * angular.module('mySceApp', ['ngSanitize']) 19600 * .controller('AppController', ['$http', '$templateCache', '$sce', 19601 * function AppController($http, $templateCache, $sce) { 19602 * var self = this; 19603 * $http.get('test_data.json', {cache: $templateCache}).then(function(response) { 19604 * self.userComments = response.data; 19605 * }); 19606 * self.explicitlyTrustedHtml = $sce.trustAsHtml( 19607 * '<span onmouseover="this.textContent="Explicitly trusted HTML bypasses ' + 19608 * 'sanitization."">Hover over this text.</span>'); 19609 * }]); 19610 * </file> 19611 * 19612 * <file name="test_data.json"> 19613 * [ 19614 * { "name": "Alice", 19615 * "htmlComment": 19616 * "<span onmouseover='this.textContent=\"PWN3D!\"'>Is <i>anyone</i> reading this?</span>" 19617 * }, 19618 * { "name": "Bob", 19619 * "htmlComment": "<i>Yes!</i> Am I the only other one?" 19620 * } 19621 * ] 19622 * </file> 19623 * 19624 * <file name="protractor.js" type="protractor"> 19625 * describe('SCE doc demo', function() { 19626 * it('should sanitize untrusted values', function() { 19627 * expect(element.all(by.css('.htmlComment')).first().getAttribute('innerHTML')) 19628 * .toBe('<span>Is <i>anyone</i> reading this?</span>'); 19629 * }); 19630 * 19631 * it('should NOT sanitize explicitly trusted values', function() { 19632 * expect(element(by.id('explicitlyTrustedHtml')).getAttribute('innerHTML')).toBe( 19633 * '<span onmouseover="this.textContent="Explicitly trusted HTML bypasses ' + 19634 * 'sanitization."">Hover over this text.</span>'); 19635 * }); 19636 * }); 19637 * </file> 19638 * </example> 19639 * 19640 * 19641 * 19642 * ## Can I disable SCE completely? 19643 * 19644 * Yes, you can. However, this is strongly discouraged. SCE gives you a lot of security benefits 19645 * for little coding overhead. It will be much harder to take an SCE disabled application and 19646 * either secure it on your own or enable SCE at a later stage. It might make sense to disable SCE 19647 * for cases where you have a lot of existing code that was written before SCE was introduced and 19648 * you're migrating them a module at a time. Also do note that this is an app-wide setting, so if 19649 * you are writing a library, you will cause security bugs applications using it. 19650 * 19651 * That said, here's how you can completely disable SCE: 19652 * 19653 * ``` 19654 * angular.module('myAppWithSceDisabledmyApp', []).config(function($sceProvider) { 19655 * // Completely disable SCE. For demonstration purposes only! 19656 * // Do not use in new projects or libraries. 19657 * $sceProvider.enabled(false); 19658 * }); 19659 * ``` 19660 * 19661 */ 19662 19663function $SceProvider() { 19664 var enabled = true; 19665 19666 /** 19667 * @ngdoc method 19668 * @name $sceProvider#enabled 19669 * @kind function 19670 * 19671 * @param {boolean=} value If provided, then enables/disables SCE application-wide. 19672 * @return {boolean} True if SCE is enabled, false otherwise. 19673 * 19674 * @description 19675 * Enables/disables SCE and returns the current value. 19676 */ 19677 this.enabled = function(value) { 19678 if (arguments.length) { 19679 enabled = !!value; 19680 } 19681 return enabled; 19682 }; 19683 19684 19685 /* Design notes on the default implementation for SCE. 19686 * 19687 * The API contract for the SCE delegate 19688 * ------------------------------------- 19689 * The SCE delegate object must provide the following 3 methods: 19690 * 19691 * - trustAs(contextEnum, value) 19692 * This method is used to tell the SCE service that the provided value is OK to use in the 19693 * contexts specified by contextEnum. It must return an object that will be accepted by 19694 * getTrusted() for a compatible contextEnum and return this value. 19695 * 19696 * - valueOf(value) 19697 * For values that were not produced by trustAs(), return them as is. For values that were 19698 * produced by trustAs(), return the corresponding input value to trustAs. Basically, if 19699 * trustAs is wrapping the given values into some type, this operation unwraps it when given 19700 * such a value. 19701 * 19702 * - getTrusted(contextEnum, value) 19703 * This function should return the a value that is safe to use in the context specified by 19704 * contextEnum or throw and exception otherwise. 19705 * 19706 * NOTE: This contract deliberately does NOT state that values returned by trustAs() must be 19707 * opaque or wrapped in some holder object. That happens to be an implementation detail. For 19708 * instance, an implementation could maintain a registry of all trusted objects by context. In 19709 * such a case, trustAs() would return the same object that was passed in. getTrusted() would 19710 * return the same object passed in if it was found in the registry under a compatible context or 19711 * throw an exception otherwise. An implementation might only wrap values some of the time based 19712 * on some criteria. getTrusted() might return a value and not throw an exception for special 19713 * constants or objects even if not wrapped. All such implementations fulfill this contract. 19714 * 19715 * 19716 * A note on the inheritance model for SCE contexts 19717 * ------------------------------------------------ 19718 * I've used inheritance and made RESOURCE_URL wrapped types a subtype of URL wrapped types. This 19719 * is purely an implementation details. 19720 * 19721 * The contract is simply this: 19722 * 19723 * getTrusted($sce.RESOURCE_URL, value) succeeding implies that getTrusted($sce.URL, value) 19724 * will also succeed. 19725 * 19726 * Inheritance happens to capture this in a natural way. In some future, we may
19726not use 19727 * inheritance anymore. That is OK because no code outside of sce.js and sceSpecs.js would need to 19728 * be aware of this detail. 19729 */ 19730 19731 this.$get = ['$parse', '$sceDelegate', function( 19732 $parse, $sceDelegate) { 19733 // Support: IE 9-11 only 19734 // Prereq: Ensure that we're not running in IE<11 quirks mode. In that mode, IE < 11 allow 19735 // the "expression(javascript expression)" syntax which is insecure. 19736 if (enabled && msie < 8) { 19737 throw $sceMinErr('iequirks', 19738 'Strict Contextual Escaping does not support Internet Explorer version < 11 in quirks ' + 19739 'mode. You can fix this by adding the text <!doctype html> to the top of your HTML ' + 19740 'document. See http://docs.angularjs.org/api/ng.$sce for more information.'); 19741 } 19742 19743 var sce = shallowCopy(SCE_CONTEXTS); 19744 19745 /** 19746 * @ngdoc method 19747 * @name $sce#isEnabled 19748 * @kind function 19749 * 19750 * @return {Boolean} True if SCE is enabled, false otherwise. If you want to set the value, you 19751 * have to do it at module config time on {@link ng.$sceProvider $sceProvider}. 19752 * 19753 * @description 19754 * Returns a boolean indicating if SCE is enabled. 19755 */ 19756 sce.isEnabled = function() { 19757 return enabled; 19758 }; 19759 sce.trustAs = $sceDelegate.trustAs; 19760 sce.getTrusted = $sceDelegate.getTrusted; 19761 sce.valueOf = $sceDelegate.valueOf; 19762 19763 if (!enabled) { 19764 sce.trustAs = sce.getTrusted = function(type, value) { return value; }; 19765 sce.valueOf = identity; 19766 } 19767 19768 /** 19769 * @ngdoc method 19770 * @name $sce#parseAs 19771 * 19772 * @description 19773 * Converts Angular
vendor: 15,534 bytes, lines 19773-20154
19773 {@link guide/expression expression} into a function. This is like {@link 19774 * ng.$parse $parse} and is identical when the expression is a literal constant. Otherwise, it 19775 * wraps the expression in a call to {@link ng.$sce#getTrusted $sce.getTrusted(*type*, 19776 * *result*)} 19777 * 19778 * @param {string} type The SCE context in which this result will be used. 19779 * @param {string} expression String expression to compile. 19780 * @return {function(context, locals)} A function which represents the compiled expression: 19781 * 19782 * * `context` – `{object}` – an object against which any expressions embedded in the 19783 * strings are evaluated against (typically a scope object). 19784 * * `locals` – `{object=}` – local variables context object, useful for overriding values 19785 * in `context`. 19786 */ 19787 sce.parseAs = function sceParseAs(type, expr) { 19788 var parsed = $parse(expr); 19789 if (parsed.literal && parsed.constant) { 19790 return parsed; 19791 } else { 19792 return $parse(expr, function(value) { 19793 return sce.getTrusted(type, value); 19794 }); 19795 } 19796 }; 19797 19798 /** 19799 * @ngdoc method 19800 * @name $sce#trustAs 19801 * 19802 * @description 19803 * Delegates to {@link ng.$sceDelegate#trustAs `$sceDelegate.trustAs`}. As such, returns a 19804 * wrapped object that represents your value, and the trust you have in its safety for the given 19805 * context. AngularJS can then use that value as-is in bindings of the specified secure context. 19806 * This is used in bindings for `ng-bind-html`, `ng-include`, and most `src` attribute 19807 * interpolations. See {@link ng.$sce $sce} for strict contextual escaping. 19808 * 19809 * @param {string} type The context in which this value is safe for use, e.g. `$sce.URL`, 19810 * `$sce.RESOURCE_URL`, `$sce.HTML`, `$sce.JS` or `$sce.CSS`. 19811 * 19812 * @param {*} value The value that that should be considered trusted. 19813 * @return {*} A wrapped version of value that can be used as a trusted variant of your `value` 19814 * in the context you specified. 19815 */ 19816 19817 /** 19818 * @ngdoc method 19819 * @name $sce#trustAsHtml 19820 * 19821 * @description 19822 * Shorthand method. `$sce.trustAsHtml(value)` → 19823 * {@link ng.$sceDelegate#trustAs `$sceDelegate.trustAs($sce.HTML, value)`} 19824 * 19825 * @param {*} value The value to mark as trusted for `$sce.HTML` context. 19826 * @return {*} A wrapped version of value that can be used as a trusted variant of your `value` 19827 * in `$sce.HTML` context (like `ng-bind-html`). 19828 */ 19829 19830 /** 19831 * @ngdoc method 19832 * @name $sce#trustAsCss 19833 * 19834 * @description 19835 * Shorthand method. `$sce.trustAsCss(value)` → 19836 * {@link ng.$sceDelegate#trustAs `$sceDelegate.trustAs($sce.CSS, value)`} 19837 * 19838 * @param {*} value The value to mark as trusted for `$sce.CSS` context. 19839 * @return {*} A wrapped version of value that can be used as a trusted variant 19840 * of your `value` in `$sce.CSS` context. This context is currently unused, so there are 19841 * almost no reasons to use this function so far. 19842 */ 19843 19844 /** 19845 * @ngdoc method 19846 * @name $sce#trustAsUrl 19847 * 19848 * @description 19849 * Shorthand method. `$sce.trustAsUrl(value)` → 19850 * {@link ng.$sceDelegate#trustAs `$sceDelegate.trustAs($sce.URL, value)`} 19851 * 19852 * @param {*} value The value to mark as trusted for `$sce.URL` context. 19853 * @return {*} A wrapped version of value that can be used as a trusted variant of your `value` 19854 * in `$sce.URL` context. That context is currently unused, so there are almost no reasons 19855 * to use this function so far. 19856 */ 19857 19858 /** 19859 * @ngdoc method 19860 * @name $sce#trustAsResourceUrl 19861 * 19862 * @description 19863 * Shorthand method. `$sce.trustAsResourceUrl(value)` → 19864 * {@link ng.$sceDelegate#trustAs `$sceDelegate.trustAs($sce.RESOURCE_URL, value)`} 19865 * 19866 * @param {*} value The value to mark as trusted for `$sce.RESOURCE_URL` context. 19867 * @return {*} A wrapped version of value that can be used as a trusted variant of your `value` 19868 * in `$sce.RESOURCE_URL` context (template URLs in `ng-include`, most `src` attribute 19869 * bindings, ...) 19870 */ 19871 19872 /** 19873 * @ngdoc method 19874 * @name $sce#trustAsJs 19875 * 19876 * @description 19877 * Shorthand method. `$sce.trustAsJs(value)` → 19878 * {@link ng.$sceDelegate#trustAs `$sceDelegate.trustAs($sce.JS, value)`} 19879 * 19880 * @param {*} value The value to mark as trusted for `$sce.JS` context. 19881 * @return {*} A wrapped version of value that can be used as a trusted variant of your `value` 19882 * in `$sce.JS` context. That context is currently unused, so there are almost no reasons to 19883 * use this function so far. 19884 */ 19885 19886 /** 19887 * @ngdoc method 19888 * @name $sce#getTrusted 19889 * 19890 * @description 19891 * Delegates to {@link ng.$sceDelegate#getTrusted `$sceDelegate.getTrusted`}. As such, 19892 * takes any input, and either returns a value that's safe to use in the specified context, 19893 * or throws an exception. This function is aware of trusted values created by the `trustAs` 19894 * function and its shorthands, and when contexts are appropriate, returns the unwrapped value 19895 * as-is. Finally, this function can also throw when there is no way to turn `maybeTrusted` in a 19896 * safe value (e.g., no sanitization is available or possible.) 19897 * 19898 * @param {string} type The context in which this value is to be used. 19899 * @param {*} maybeTrusted The result of a prior {@link ng.$sce#trustAs 19900 * `$sce.trustAs`} call, or anything else (which will not be considered trusted.) 19901 * @return {*} A version of the value that's safe to use in the given context, or throws an 19902 * exception if this is impossible. 19903 */ 19904 19905 /** 19906 * @ngdoc method 19907 * @name $sce#getTrustedHtml 19908 * 19909 * @description 19910 * Shorthand method. `$sce.getTrustedHtml(value)` → 19911 * {@link ng.$sceDelegate#getTrusted `$sceDelegate.getTrusted($sce.HTML, value)`} 19912 * 19913 * @param {*} value The value to pass to `$sce.getTrusted`. 19914 * @return {*} The return value of `$sce.getTrusted($sce.HTML, value)` 19915 */ 19916 19917 /** 19918 * @ngdoc method 19919 * @name $sce#getTrustedCss 19920 * 19921 * @description 19922 * Shorthand method. `$sce.getTrustedCss(value)` → 19923 * {@link ng.$sceDelegate#getTrusted `$sceDelegate.getTrusted($sce.CSS, value)`} 19924 * 19925 * @param {*} value The value to pass to `$sce.getTrusted`. 19926 * @return {*} The return value of `$sce.getTrusted($sce.CSS, value)` 19927 */ 19928 19929 /** 19930 * @ngdoc method 19931 * @name $sce#getTrustedUrl 19932 * 19933 * @description 19934 * Shorthand method. `$sce.getTrustedUrl(value)` → 19935 * {@link ng.$sceDelegate#getTrusted `$sceDelegate.getTrusted($sce.URL, value)`} 19936 * 19937 * @param {*} value The value to pass to `$sce.getTrusted`. 19938 * @return {*} The return value of `$sce.getTrusted($sce.URL, value)` 19939 */ 19940 19941 /** 19942 * @ngdoc method 19943 * @name $sce#getTrustedResourceUrl 19944 * 19945 * @description 19946 * Shorthand method. `$sce.getTrustedResourceUrl(value)` → 19947 * {@link ng.$sceDelegate#getTrusted `$sceDelegate.getTrusted($sce.RESOURCE_URL, value)`} 19948 * 19949 * @param {*} value The value to pass to `$sceDelegate.getTrusted`. 19950 * @return {*} The return value of `$sce.getTrusted($sce.RESOURCE_URL, value)` 19951 */ 19952 19953 /** 19954 * @ngdoc method 19955 * @name $sce#getTrustedJs 19956 * 19957 * @description 19958 * Shorthand method. `$sce.getTrustedJs(value)` → 19959 * {@link ng.$sceDelegate#getTrusted `$sceDelegate.getTrusted($sce.JS, value)`} 19960 * 19961 * @param {*} value The value to pass to `$sce.getTrusted`. 19962 * @return {*} The return value of `$sce.getTrusted($sce.JS, value)` 19963 */ 19964 19965 /** 19966 * @ngdoc method 19967 * @name $sce#parseAsHtml 19968 * 19969 * @description 19970 * Shorthand method. `$sce.parseAsHtml(expression string)` → 19971 * {@link ng.$sce#parseAs `$sce.parseAs($sce.HTML, value)`} 19972 * 19973 * @param {string} expression String expression to compile. 19974 * @return {function(context, locals)} A function which represents the compiled expression: 19975 * 19976 * * `context` – `{object}` – an object against which any expressions embedded in the 19977 * strings are evaluated against (typically a scope object). 19978 * * `locals` – `{object=}` – local variables context object, useful for overriding values 19979 * in `context`. 19980 */ 19981 19982 /** 19983 * @ngdoc method 19984 * @name $sce#parseAsCss 19985 * 19986 * @description 19987 * Shorthand method. `$sce.parseAsCss(value)` → 19988 * {@link ng.$sce#parseAs `$sce.parseAs($sce.CSS, value)`} 19989 * 19990 * @param {string} expression String expression to compile. 19991 * @return {function(context, locals)} A function which represents the compiled expression: 19992 * 19993 * * `context` – `{object}` – an object against which any expressions embedded in the 19994 * strings are evaluated against (typically a scope object). 19995 * * `locals` – `{object=}` – local variables context object, useful for overriding values 19996 * in `context`. 19997 */ 19998 19999 /** 20000 * @ngdoc method 20001 * @name $sce#parseAsUrl 20002 * 20003 * @description 20004 * Shorthand method. `$sce.parseAsUrl(value)` → 20005 * {@link ng.$sce#parseAs `$sce.parseAs($sce.URL, value)`} 20006 * 20007 * @param {string} expression String expression to compile. 20008 * @return {function(context, locals)} A function which represents the compiled expression: 20009 * 20010 * * `context` – `{object}` – an object against which any expressions embedded in the 20011 * strings are evaluated against (typically a scope object). 20012 * * `locals` – `{object=}` – local variables context object, useful for overriding values 20013 * in `context`. 20014 */ 20015 20016 /** 20017 * @ngdoc method 20018 * @name $sce#parseAsResourceUrl 20019 * 20020 * @description 20021 * Shorthand method. `$sce.parseAsResourceUrl(value)` → 20022 * {@link ng.$sce#parseAs `$sce.parseAs($sce.RESOURCE_URL, value)`} 20023 * 20024 * @param {string} expression String expression to compile. 20025 * @return {function(context, locals)} A function which represents the compiled expression: 20026 * 20027 * * `context` – `{object}` – an object against which any expressions embedded in the 20028 * strings are evaluated against (typically a scope object). 20029 * * `locals` – `{object=}` – local variables context object, useful for overriding values 20030 * in `context`. 20031 */ 20032 20033 /** 20034 * @ngdoc method 20035 * @name $sce#parseAsJs 20036 * 20037 * @description 20038 * Shorthand method. `$sce.parseAsJs(value)` → 20039 * {@link ng.$sce#parseAs `$sce.parseAs($sce.JS, value)`} 20040 * 20041 * @param {string} expression String expression to compile. 20042 * @return {function(context, locals)} A function which represents the compiled expression: 20043 * 20044 * * `context` – `{object}` – an object against which any expressions embedded in the 20045 * strings are evaluated against (typically a scope object). 20046 * * `locals` – `{object=}` – local variables context object, useful for overriding values 20047 * in `context`. 20048 */ 20049 20050 // Shorthand delegations. 20051 var parse = sce.parseAs, 20052 getTrusted = sce.getTrusted, 20053 trustAs = sce.trustAs; 20054 20055 forEach(SCE_CONTEXTS, function(enumValue, name) { 20056 var lName = lowercase(name); 20057 sce[snakeToCamel('parse_as_' + lName)] = function(expr) { 20058 return parse(enumValue, expr); 20059 }; 20060 sce[snakeToCamel('get_trusted_' + lName)] = function(value) { 20061 return getTrusted(enumValue, value); 20062 }; 20063 sce[snakeToCamel('trust_as_' + lName)] = function(value) { 20064 return trustAs(enumValue, value); 20065 }; 20066 }); 20067 20068 return sce; 20069 }]; 20070} 20071 20072/* exported $SnifferProvider */ 20073 20074/** 20075 * !!! This is an undocumented "private" service !!! 20076 * 20077 * @name $sniffer 20078 * @requires $window 20079 * @requires $document 20080 * @this 20081 * 20082 * @property {boolean} history Does the browser support html5 history api ? 20083 * @property {boolean} transitions Does the browser support CSS transition events ? 20084 * @property {boolean} animations Does the browser support CSS animation events ? 20085 * 20086 * @description 20087 * This is very simple implementation of testing browser's features. 20088 */ 20089function $SnifferProvider() { 20090 this.$get = ['$window', '$document', function($window, $document) { 20091 var eventSupport = {}, 20092 // Chrome Packaged Apps are not allowed to access `history.pushState`. 20093 // If not sandboxed, they can be detected by the presence of `chrome.app.runtime` 20094 // (see https://developer.chrome.com/apps/api_index). If sandboxed, they can be detected by 20095 // the presence of an extension runtime ID and the absence of other Chrome runtime APIs 20096 // (see https://developer.chrome.com/apps/manifest/sandbox). 20097 // (NW.js apps have access to Chrome APIs, but do support `history`.) 20098 isNw = $window.nw && $window.nw.process, 20099 isChromePackagedApp = 20100 !isNw && 20101 $window.chrome && 20102 ($window.chrome.app && $window.chrome.app.runtime || 20103 !$window.chrome.app && $window.chrome.runtime && $window.chrome.runtime.id), 20104 hasHistoryPushState = !isChromePackagedApp && $window.history && $window.history.pushState, 20105 android = 20106 toInt((/android (\d+)/.exec(lowercase(($window.navigator || {}).userAgent)) || [])[1]), 20107 boxee = /Boxee/i.test(($window.navigator || {}).userAgent), 20108 document = $document[0] || {}, 20109 bodyStyle = document.body && document.body.style, 20110 transitions = false, 20111 animations = false; 20112 20113 if (bodyStyle) { 20114 // Support: Android <5, Blackberry Browser 10, default Chrome in Android 4.4.x 20115 // Mentioned browsers need a -webkit- prefix for transitions & animations. 20116 transitions = !!('transition' in bodyStyle || 'webkitTransition' in bodyStyle); 20117 animations = !!('animation' in bodyStyle || 'webkitAnimation' in bodyStyle); 20118 } 20119 20120 20121 return { 20122 // Android has history.pushState, but it does not update location correctly 20123 // so let's not use the history API at all. 20124 // http://code.google.com/p/android/issues/detail?id=17471 20125 // https://github.com/angular/angular.js/issues/904 20126 20127 // older webkit browser (533.9) on Boxee box has exactly the same problem as Android has 20128 // so let's not use the history API also 20129 // We are purposefully using `!(android < 4)` to cover the case when `android` is undefined 20130 history: !!(hasHistoryPushState && !(android < 4) && !boxee), 20131 hasEvent: function(event) { 20132 // Support: IE 9-11 only 20133 // IE9 implements 'input' event it's so fubared that we rather pretend that it doesn't have 20134 // it. In particular the event is not fired when backspace or delete key are pressed or 20135 // when cut operation is performed. 20136 // IE10+ implements 'input' event but it erroneously fires under various situations, 20137 // e.g. when placeholder changes, or a form is focused. 20138 if (event === 'input' && msie) return false; 20139 20140 if (isUndefined(eventSupport[event])) { 20141 var divElm = document.createElement('div'); 20142 eventSupport[event] = 'on' + event in divElm; 20143 } 20144 20145 return eventSupport[event]; 20146 }, 20147 csp: csp(), 20148 transitions: transitions, 20149 animations: animations, 20150 android: android 20151 }; 20152 }]; 20153} 20154
20155var $templateRequestMinErr = minErr('$compile'); 20156 20157/** 20158 * @ngdoc provider 20159 * @name $templateRequestProvider 20160 * @this 20161 * 20162 * @description 20163 * Used to configure the options passed to the {@link $http} service when making a template request. 20164 * 20165 * For example, it can be used for specifying the "Accept" header that is sent to the server, when 20166 * requesting a template. 20167 */ 20168function $TemplateRequestProvider() { 20169 20170 var httpOptions; 20171 20172 /** 20173 * @ngdoc method 20174 * @name $templateRequestProvider#httpOptions 20175 * @description 20176 * The options to be passed to the {@link $http} service when making the request. 20177 * You can use this to override options such as the "Accept" header for template requests. 20178 * 20179 * The {@link $templateRequest} will set the `cache` and the `transformResponse` properties of the 20180 * options if not overridden here. 20181 * 20182 * @param {string=} value new value for the {@link $http} options. 20183 * @returns {string|self} Returns the {@link $http} options when used as getter and self if used as setter. 20184 */ 20185 this.httpOptions = function(val) { 20186 if (val) { 20187 httpOptions = val; 20188 return this; 20189 } 20190 return httpOptions; 20191 }; 20192 20193 /** 20194 * @ngdoc service 20195 * @name $templateRequest 20196 * 20197 * @description 20198 * The `$templateRequest` service runs security checks then downloads the provided template using 20199 * `$http` and, upon success, stores the contents inside of `$templateCache`. If the HTTP request 20200 * fails or the response data of the HTTP request is empty, a `$compile` error will be thrown (the 20201 * exception can be thwarted by setting the 2nd parameter of the function to true). Note that the 20202 * contents of `$templateCache` are trusted, so the call to `$sce.getTrustedUrl(tpl)` is omitted 20203 * when `tpl` is of type string and `$templateCache` has the matching entry. 20204 * 20205 * If you want to pass custom options to the `$http` service, such as setting the Accept header you 20206 * can configure this via {@link $templateRequestProvider#httpOptions}. 20207 * 20208 * @param {string|TrustedResourceUrl} tpl The HTTP request template URL 20209 * @param {boolean=} ignoreRequestError Whether or not to ignore the exception when the request fails or the template is empty 20210 * 20211 * @return {Promise} a promise for the HTTP response data of the given URL. 20212 * 20213 * @property {number} totalPendingRequests total amount of pending template requests being downloaded.
vendor: 4,630 bytes, lines 20214-20347
20214 */ 20215 this.$get = ['$exceptionHandler', '$templateCache', '$http', '$q', '$sce', 20216 function($exceptionHandler, $templateCache, $http, $q, $sce) { 20217 20218 function handleRequestFn(tpl, ignoreRequestError) { 20219 handleRequestFn.totalPendingRequests++; 20220 20221 // We consider the template cache holds only trusted templates, so 20222 // there's no need to go through whitelisting again for keys that already 20223 // are included in there. This also makes Angular accept any script 20224 // directive, no matter its name. However, we still need to unwrap trusted 20225 // types. 20226 if (!isString(tpl) || isUndefined($templateCache.get(tpl))) { 20227 tpl = $sce.getTrustedResourceUrl(tpl); 20228 } 20229 20230 var transformResponse = $http.defaults && $http.defaults.transformResponse; 20231 20232 if (isArray(transformResponse)) { 20233 transformResponse = transformResponse.filter(function(transformer) { 20234 return transformer !== defaultHttpResponseTransform; 20235 }); 20236 } else if (transformResponse === defaultHttpResponseTransform) { 20237 transformResponse = null; 20238 } 20239 20240 return $http.get(tpl, extend({ 20241 cache: $templateCache, 20242 transformResponse: transformResponse 20243 }, httpOptions)) 20244 .finally(function() { 20245 handleRequestFn.totalPendingRequests--; 20246 }) 20247 .then(function(response) { 20248 $templateCache.put(tpl, response.data); 20249 return response.data; 20250 }, handleError); 20251 20252 function handleError(resp) { 20253 if (!ignoreRequestError) { 20254 resp = $templateRequestMinErr('tpload', 20255 'Failed to load template: {0} (HTTP status: {1} {2})', 20256 tpl, resp.status, resp.statusText); 20257 20258 $exceptionHandler(resp); 20259 } 20260 20261 return $q.reject(resp); 20262 } 20263 } 20264 20265 handleRequestFn.totalPendingRequests = 0; 20266 20267 return handleRequestFn; 20268 } 20269 ]; 20270} 20271 20272/** @this */ 20273function $$TestabilityProvider() { 20274 this.$get = ['$rootScope', '$browser', '$location', 20275 function($rootScope, $browser, $location) { 20276 20277 /** 20278 * @name $testability 20279 * 20280 * @description 20281 * The private $$testability service provides a collection of methods for use when debugging 20282 * or by automated test and debugging tools. 20283 */ 20284 var testability = {}; 20285 20286 /** 20287 * @name $$testability#findBindings 20288 * 20289 * @description 20290 * Returns an array of elements that are bound (via ng-bind or {{}}) 20291 * to expressions matching the input. 20292 * 20293 * @param {Element} element The element root to search from. 20294 * @param {string} expression The binding expression to match. 20295 * @param {boolean} opt_exactMatch If true, only returns exact matches 20296 * for the expression. Filters and whitespace are ignored. 20297 */ 20298 testability.findBindings = function(element, expression, opt_exactMatch) { 20299 var bindings = element.getElementsByClassName('ng-binding'); 20300 var matches = []; 20301 forEach(bindings, function(binding) { 20302 var dataBinding = angular.element(binding).data('$binding'); 20303 if (dataBinding) { 20304 forEach(dataBinding, function(bindingName) { 20305 if (opt_exactMatch) { 20306 var matcher = new RegExp('(^|\\s)' + escapeForRegexp(expression) + '(\\s|\\||$)'); 20307 if (matcher.test(bindingName)) { 20308 matches.push(binding); 20309 } 20310 } else { 20311 if (bindingName.indexOf(expression) !== -1) { 20312 matches.push(binding); 20313 } 20314 } 20315 }); 20316 } 20317 }); 20318 return matches; 20319 }; 20320 20321 /** 20322 * @name $$testability#findModels 20323 * 20324 * @description 20325 * Returns an array of elements that are two-way found via ng-model to 20326 * expressions matching the input. 20327 * 20328 * @param {Element} element The element root to search from. 20329 * @param {string} expression The model expression to match. 20330 * @param {boolean} opt_exactMatch If true, only returns exact matches 20331 * for the expression. 20332 */ 20333 testability.findModels = function(element, expression, opt_exactMatch) { 20334 var prefixes = ['ng-', 'data-ng-', 'ng\\:']; 20335 for (var p = 0; p < prefixes.length; ++p) { 20336 var attributeEquals = opt_exactMatch ? '=' : '*='; 20337 var selector = '[' + prefixes[p] + 'model' + attributeEquals + '"' + expression + '"]'; 20338 var elements = element.querySelectorAll(selector); 20339 if (elements.length) { 20340 return elements; 20341 } 20342 } 20343 }; 20344 20345 /** 20346 * @name $$testability#getLocation 20347 *
20348 * @description 20349 * Shortcut for getting the location in a browser agnostic way. Returns 20350 * the path, search, and hash. (e.g. /path?a=b#hash) 20351 */ 20352 testability.getLocation = function() { 20353 return $location.url(); 20354 }; 20355 20356 /** 20357 * @name $$testability#setLocation 20358 * 20359 * @description 20360 * Shortcut for navigating to a location without doing a full page reload. 20361 * 20362 * @param {string} url The location url (path, search and hash, 20363 * e.g. /path?a=b#hash) to go to. 20364 */ 20365 testability.setLocation = function(url) { 20366 if (url !== $location.url()) { 20367 $location.url(url); 20368 $rootScope.$digest(); 20369 } 20370 }; 20371 20372 /** 20373 * @name $$testability#whenStable 20374 * 20375 * @description 20376 * Calls the callback when $timeout and $http requests are completed. 20377 * 20378 * @param {function} callback 20379 */ 20380 testability.whenStable = function(callback) { 20381 $browser.notifyWhenNoOutstandingRequests(callback); 20382 }; 20383 20384 return testability; 20385 }]; 20386} 20387 20388/** @this */ 20389function $TimeoutProvider() { 20390 this.$get = ['$rootScope', '$browser', '$q', '$$q', '$exceptionHandler', 20391 function($rootScope, $browser, $q, $$q, $exceptionHandler) { 20392 20393 var deferreds = {}; 20394 20395 20396 /** 20397 * @ngdoc service 20398 * @name $timeout 20399 * 20400 * @description 20401 * Angular's wrapper for `window.setTimeout`. The `fn` function is wrapped into a try/catch 20402 * block and delegates any exceptions to 20403 * {@link ng.$exceptionHandler $exceptionHandler} service. 20404 * 20405 * The return value of calling `$timeout` is a promise, which will be resolved when 20406 * the delay has passed and the timeout function, if provided, is executed. 20407 * 20408 * To cancel a timeout request, call `$timeout.cancel(promise)`. 20409 * 20410 * In tests you can use {@link ngMock.$timeout `$timeout.flush()`} to 20411 * synchronously flush the queue of deferred functions. 20412 * 20413 * If you only want a promise that will be resolved after some specified delay 20414 * then you can call `$timeout` without the `fn` function. 20415 * 20416 * @param {function()=} fn A function, whose execution should be delayed. 20417 * @param {number=} [delay=0] Delay in milliseconds. 20418 * @param {boolean=} [invokeApply=true] If set to `false` skips model dirty checking, otherwise 20419 * will invoke `fn` within the {@link ng.$rootScope.Scope#$apply $apply} block. 20420 * @param {...*=} Pass additional parameters to the executed function. 20421 * @returns {Promise} Promise that will be resolved when the timeout is reached. The promise 20422 * will be resolved with the return value of the `fn` function. 20423 * 20424 */ 20425 function timeout(fn, delay, invokeApply) { 20426 if (!isFunction(fn)) { 20427 invokeApply = delay; 20428 delay = fn; 20429 fn = noop; 20430 } 20431 20432 var args = sliceArgs(arguments, 3), 20433 skipApply = (isDefined(invokeApply) && !invokeApply), 20434 deferred = (skipApply ? $$q : $q).defer(), 20435 promise = deferred.promise, 20436 timeoutId; 20437 20438 timeoutId = $browser.defer(function() { 20439 try { 20440 deferred.resolve(fn.apply(null, args)); 20441 } catch (e) { 20442 deferred.reject(e); 20443 $exceptionHandler(e); 20444 } finally { 20445 delete deferreds[promise.$$timeoutId]; 20446 } 20447 20448 if (!skipApply) $rootScope.$apply(); 20449 }, delay); 20450 20451 promise.$$timeoutId = timeoutId; 20452 deferreds[timeoutId] = deferred; 20453 20454 return promise; 20455 } 20456 20457 20458 /** 20459 * @ngdoc method 20460 * @name $timeout#cancel 20461 * 20462 * @description 20463 * Cancels a task associated with the `promise`. As a result of this, the promise will be 20464 * resolved with a rejection. 20465 * 20466 * @param {Promise=} promise Promise returned by the `$timeout` function. 20467 * @returns {boolean} Returns `true` if the task hasn't executed yet and was successfully 20468 * canceled. 20469 */ 20470 timeout.cancel = function(promise) { 20471 if (promise && promise.$$timeoutId in deferreds) { 20472 // Timeout cancels should not report an unhandled promise. 20473 markQExceptionHandled(deferreds[promise.$$timeoutId].promise); 20474 deferreds[promise.$$timeoutId].reject('canceled'); 20475 delete deferreds[promise.$$timeoutId]; 20476 return $browser.defer.cancel(promise.$$timeoutId); 20477 } 20478 return false;
vendor: 5,388 bytes, lines 20479-20602
20479 }; 20480 20481 return timeout; 20482 }]; 20483} 20484 20485// NOTE: The usage of window and document instead of $window and $document here is 20486// deliberate. This service depends on the specific behavior of anchor nodes created by the 20487// browser (resolving and parsing URLs) that is unlikely to be provided by mock objects and 20488// cause us to break tests. In addition, when the browser resolves a URL for XHR, it 20489// doesn't know about mocked locations and resolves URLs to the real document - which is 20490// exactly the behavior needed here. There is little value is mocking these out for this 20491// service. 20492var urlParsingNode = window.document.createElement('a'); 20493var originUrl = urlResolve(window.location.href); 20494 20495 20496/** 20497 * 20498 * Implementation Notes for non-IE browsers 20499 * ---------------------------------------- 20500 * Assigning a URL to the href property of an anchor DOM node, even one attached to the DOM, 20501 * results both in the normalizing and parsing of the URL. Normalizing means that a relative 20502 * URL will be resolved into an absolute URL in the context of the application document. 20503 * Parsing means that the anchor node's host, hostname, protocol, port, pathname and related 20504 * properties are all populated to reflect the normalized URL. This approach has wide 20505 * compatibility - Safari 1+, Mozilla 1+ etc. See 20506 * http://www.aptana.com/reference/html/api/HTMLAnchorElement.html 20507 * 20508 * Implementation Notes for IE 20509 * --------------------------- 20510 * IE <= 10 normalizes the URL when assigned to the anchor node similar to the other 20511 * browsers. However, the parsed components will not be set if the URL assigned did not specify 20512 * them. (e.g. if you assign a.href = "foo", then a.protocol, a.host, etc. will be empty.) We 20513 * work around that by performing the parsing in a 2nd step by taking a previously normalized 20514 * URL (e.g. by assigning to a.href) and assigning it a.href again. This correctly populates the 20515 * properties such as protocol, hostname, port, etc. 20516 * 20517 * References: 20518 * http://developer.mozilla.org/en-US/docs/Web/API/HTMLAnchorElement 20519 * http://www.aptana.com/reference/html/api/HTMLAnchorElement.html 20520 * http://url.spec.whatwg.org/#urlutils 20521 * https://github.com/angular/angular.js/pull/2902 20522 * http://james.padolsey.com/javascript/parsing-urls-with-the-dom/ 20523 * 20524 * @kind function 20525 * @param {string} url The URL to be parsed. 20526 * @description Normalizes and parses a URL. 20527 * @returns {object} Returns the normalized URL as a dictionary. 20528 * 20529 * | member name | Description | 20530 * |---------------|----------------| 20531 * | href | A normalized version of the provided URL if it was not an absolute URL | 20532 * | protocol | The protocol including the trailing colon | 20533 * | host | The host and port (if the port is non-default) of the normalizedUrl | 20534 * | search | The search params, minus the question mark | 20535 * | hash | The hash string, minus the hash symbol 20536 * | hostname | The hostname 20537 * | port | The port, without ":" 20538 * | pathname | The pathname, beginning with "/" 20539 * 20540 */ 20541function urlResolve(url) { 20542 var href = url; 20543 20544 // Support: IE 9-11 only 20545 if (msie) { 20546 // Normalize before parse. Refer Implementation Notes on why this is 20547 // done in two steps on IE. 20548 urlParsingNode.setAttribute('href', href); 20549 href = urlParsingNode.href; 20550 } 20551 20552 urlParsingNode.setAttribute('href', href); 20553 20554 // urlParsingNode provides the UrlUtils interface - http://url.spec.whatwg.org/#urlutils 20555 return { 20556 href: urlParsingNode.href, 20557 protocol: urlParsingNode.protocol ? urlParsingNode.protocol.replace(/:$/, '') : '', 20558 host: urlParsingNode.host, 20559 search: urlParsingNode.search ? urlParsingNode.search.replace(/^\?/, '') : '', 20560 hash: urlParsingNode.hash ? urlParsingNode.hash.replace(/^#/, '') : '', 20561 hostname: urlParsingNode.hostname, 20562 port: urlParsingNode.port, 20563 pathname: (urlParsingNode.pathname.charAt(0) === '/') 20564 ? urlParsingNode.pathname 20565 : '/' + urlParsingNode.pathname 20566 }; 20567} 20568 20569/** 20570 * Parse a request URL and determine whether this is a same-origin request as the application document. 20571 * 20572 * @param {string|object} requestUrl The url of the request as a string that will be resolved 20573 * or a parsed URL object. 20574 * @returns {boolean} Whether the request is for the same origin as the application document. 20575 */ 20576function urlIsSameOrigin(requestUrl) { 20577 var parsed = (isString(requestUrl)) ? urlResolve(requestUrl) : requestUrl; 20578 return (parsed.protocol === originUrl.protocol && 20579 parsed.host === originUrl.host); 20580} 20581 20582/** 20583 * @ngdoc service 20584 * @name $window 20585 * @this 20586 * 20587 * @description 20588 * A reference to the browser's `window` object. While `window` 20589 * is globally available in JavaScript, it causes testability problems, because 20590 * it is a global variable. In angular we always refer to it through the 20591 * `$window` service, so it may be overridden, removed or mocked for testing. 20592 * 20593 * Expressions, like the one defined for the `ngClick` directive in the example 20594 * below, are evaluated with respect to the current scope. Therefore, there is 20595 * no risk of inadvertently coding in a dependency on a global value in such an 20596 * expression. 20597 * 20598 * @example 20599 <example module="windowExample" name="window-service"> 20600 <file name="index.html"> 20601 <script> 20602 angular.module('windowExample', [])
20603 .controller('ExampleController', ['$scope', '$window', function($scope, $window) { 20604 $scope.greeting = 'Hello, World!'; 20605 $scope.doGreeting = function(greeting) { 20606 $window.alert(greeting); 20607 }; 20608 }]); 20609 </script> 20610 <div ng-controller="ExampleController"> 20611 <input type="text" ng-model="greeting" aria-label="greeting" /> 20612 <button ng-click="doGreeting(greeting)">ALERT</button> 20613 </div> 20614 </file> 20615 <file name="protractor.js" type="protractor"> 20616 it('should display the greeting in the input box', function() { 20617 element(by.model('greeting')).sendKeys('Hello, E2E Tests'); 20618 // If we click the button it will block the test runner 20619 // element(':button').click(); 20620 }); 20621 </file> 20622 </example> 20623 */ 20624function $WindowProvider() { 20625 this.$get = valueFn(window); 20626} 20627 20628/** 20629 * @name $$cookieReader 20630 * @requires $document 20631 * 20632 * @description 20633 * This is a private service for reading cookies used by $http and ngCookies 20634 * 20635 * @return {Object} a key/value map of the current cookies 20636 */ 20637function $$CookieReader($document) { 20638 var rawDocument = $document[0] || {}; 20639 var lastCookies = {}; 20640 var lastCookieString = ''; 20641 20642 function safeGetCookie(rawDocument) { 20643 try { 20644 return rawDocument.cookie || ''; 20645 } catch (e) { 20646 return ''; 20647 } 20648 } 20649 20650 function safeDecodeURIComponent(str) { 20651 try { 20652 return decodeURIComponent(str); 20653 } catch (e) { 20654 return str; 20655 } 20656 } 20657 20658 return function() { 20659 var cookieArray, cookie, i, index, name; 20660 var currentCookieString = safeGetCookie(rawDocument); 20661 20662 if (currentCookieString !== lastCookieString) { 20663 lastCookieString = currentCookieString; 20664 cookieArray = lastCookieString.split('; '); 20665 lastCookies = {}; 20666 20667 for (i = 0; i < cookieArray.length; i++) { 20668 cookie = cookieArray[i]; 20669 index = cookie.indexOf('='); 20670 if (index > 0) { //ignore nameless cookies 20671 name = safeDecodeURIComponent(cookie.substring(0, index)); 20672 // the first value that is seen for a cookie is the most 20673 // specific one. values for the same cookie name that 20674 // follow are for less specific paths. 20675 if (isUndefined(lastCookies[name])) { 20676 lastCookies[name] = safeDecodeURIComponent(cookie.substring(index + 1)); 20677 } 20678 } 20679 } 20680 } 20681 return lastCookies; 20682 }; 20683} 20684 20685$$CookieReader.$inject = ['$document']; 20686 20687/** @this */ 20688function $$CookieReaderProvider() { 20689 this.$get = $$CookieReader; 20690} 20691 20692/* global currencyFilter: true, 20693 dateFilter: true, 20694 filterFilter: true, 20695 jsonFilter: true, 20696 limitToFilter: true, 20697 lowercaseFilter: true, 20698 numberFilter: true, 20699 orderByFilter: true, 20700 uppercaseFilter: true, 20701 */ 20702 20703/** 20704 * @ngdoc provider 20705 * @name $filterProvider 20706 * @description 20707 * 20708 * Filters are just functions which transform input to an output. However filters need to be 20709 * Dependency Injected. To achieve this a filter definition consists of a factory function which is 20710 * annotated with dependencies and is responsible for creating a filter function. 20711 * 20712 * <div class="alert alert-warning"> 20713 * **Note:** Filter names must be valid angular {@link expression} identifiers, such as `uppercase` or `orderBy`. 20714 * Names with special characters, such as hyphens and dots, are not allowed. If you wish to namespace 20715 * your filters, then you can use capitalization (`myappSubsectionFilterx`) or underscores 20716 * (`myapp_subsection_filterx`). 20717 * </div> 20718 * 20719 * ```js 20720 * // Filter registration 20721 * function MyModule($provide, $filterProvider) { 20722 * // create a service to demonstrate injection (not always needed) 20723 * $provide.value('greet', function(name){ 20724 * return 'Hello ' + name + '!'; 20725 * }); 20726 * 20727 * // register a filter factory which uses the 20728 * // greet service to demonstrate DI. 20729 * $filterProvider.register('greet', function(greet){ 20730 * // return the filter function which uses the greet service 20731 * // to generate salutation 20732 * return function(text) { 20733 * // filters need to be forgiving so check input validity 20734 * return text && greet(text) || text; 20735 * }; 20736 * }); 20737 * } 20738 * ``` 20739 * 20740 * The filter function is registered with the `$injector` under the filter name suffix with 20741 * `Filter`. 20742 * 20743 * ```js 20744 * it('should be the same instance', inject( 20745 * function($filterProvider) { 20746 * $filterProvider.register('reverse', function(){ 20747 * return ...; 20748 * }); 20749 * }, 20750 * function($filter, reverseFilter) { 20751 * expect($filter('reverse')).toBe(reverseFilter); 20752 * }); 20753 * ``` 20754 * 20755 * 20756 * For more information about how angular filters work, and how to create your own filters, see 20757 * {@link guide/filter Filters} in the Angular Developer Guide. 20758 */ 20759 20760/** 20761 * @ngdoc service 20762 * @name $filter 20763 * @kind function 20764 * @description 20765 * Filters are used for formatting data displayed to the user. 20766 * 20767 * They can be used in view templates, controllers or services.Angular comes 20768 * with a collection of [built-in filters](api/ng/filter), but it is easy to 20769 * define your own as well. 20770 * 20771 * The general syntax in templates is as follows: 20772 * 20773 * ```html 20774 * {{ expression [| filter_name[:parameter_value] ... ] }} 20775 * ``` 20776 * 20777 * @param {String} name Name of the filter function to retrieve 20778 * @return {Function} the filter function 20779 * @example 20780 <example name="$filter" module="filterExample"> 20781 <file name="index.html"> 20782 <div ng-controller="MainCtrl"> 20783 <h3>{{ originalText }}</h3> 20784 <h3>{{ filteredText }}</h3> 20785 </div> 20786 </file> 20787 20788 <file name="script.js"> 20789 angular.module('filterExample', []) 20790 .controller('MainCtrl', function($scope, $filter) { 20791 $scope.originalText = 'hello'; 20792 $scope.filteredText = $filter('uppercase')($scope.originalText); 20793 }); 20794 </file> 20795 </example> 20796 */ 20797$FilterProvider.$inject = ['$provide']; 20798/** @this */ 20799function $FilterProvider($provide) { 20800 var suffix = 'Filter'; 20801 20802 /** 20803 * @ngdoc method 20804 * @name $filterProvider#register 20805 * @param {string|Object} name Name of the filter function, or an object map of filters where 20806 * the keys are the filter names and the values are the filter factories. 20807 * 20808 * <div class="alert alert-warning"> 20809 * **Note:** Filter names must be valid angular
vendor: 15,039 bytes, lines 20809-21197
20809 {@link expression} identifiers, such as `uppercase` or `orderBy`. 20810 * Names with special characters, such as hyphens and dots, are not allowed. If you wish to namespace 20811 * your filters, then you can use capitalization (`myappSubsectionFilterx`) or underscores 20812 * (`myapp_subsection_filterx`). 20813 * </div> 20814 * @param {Function} factory If the first argument was a string, a factory function for the filter to be registered. 20815 * @returns {Object} Registered filter instance, or if a map of filters was provided then a map 20816 * of the registered filter instances. 20817 */ 20818 function register(name, factory) { 20819 if (isObject(name)) { 20820 var filters = {}; 20821 forEach(name, function(filter, key) { 20822 filters[key] = register(key, filter); 20823 }); 20824 return filters; 20825 } else { 20826 return $provide.factory(name + suffix, factory); 20827 } 20828 } 20829 this.register = register; 20830 20831 this.$get = ['$injector', function($injector) { 20832 return function(name) { 20833 return $injector.get(name + suffix); 20834 }; 20835 }]; 20836 20837 //////////////////////////////////////// 20838 20839 /* global 20840 currencyFilter: false, 20841 dateFilter: false, 20842 filterFilter: false, 20843 jsonFilter: false, 20844 limitToFilter: false, 20845 lowercaseFilter: false, 20846 numberFilter: false, 20847 orderByFilter: false, 20848 uppercaseFilter: false 20849 */ 20850 20851 register('currency', currencyFilter); 20852 register('date', dateFilter); 20853 register('filter', filterFilter); 20854 register('json', jsonFilter); 20855 register('limitTo', limitToFilter); 20856 register('lowercase', lowercaseFilter); 20857 register('number', numberFilter); 20858 register('orderBy', orderByFilter); 20859 register('uppercase', uppercaseFilter); 20860} 20861 20862/** 20863 * @ngdoc filter 20864 * @name filter 20865 * @kind function 20866 * 20867 * @description 20868 * Selects a subset of items from `array` and returns it as a new array. 20869 * 20870 * @param {Array} array The source array. 20871 * <div class="alert alert-info"> 20872 * **Note**: If the array contains objects that reference themselves, filtering is not possible. 20873 * </div> 20874 * @param {string|Object|function()} expression The predicate to be used for selecting items from 20875 * `array`. 20876 * 20877 * Can be one of: 20878 * 20879 * - `string`: The string is used for matching against the contents of the `array`. All strings or 20880 * objects with string properties in `array` that match this string will be returned. This also 20881 * applies to nested object properties. 20882 * The predicate can be negated by prefixing the string with `!`. 20883 * 20884 * - `Object`: A pattern object can be used to filter specific properties on objects contained 20885 * by `array`. For example `{name:"M", phone:"1"}` predicate will return an array of items 20886 * which have property `name` containing "M" and property `phone` containing "1". A special 20887 * property name (`$` by default) can be used (e.g. as in `{$: "text"}`) to accept a match 20888 * against any property of the object or its nested object properties. That's equivalent to the 20889 * simple substring match with a `string` as described above. The special property name can be 20890 * overwritten, using the `anyPropertyKey` parameter. 20891 * The predicate can be negated by prefixing the string with `!`. 20892 * For example `{name: "!M"}` predicate will return an array of items which have property `name` 20893 * not containing "M". 20894 * 20895 * Note that a named property will match properties on the same level only, while the special 20896 * `$` property will match properties on the same level or deeper. E.g. an array item like 20897 * `{name: {first: 'John', last: 'Doe'}}` will **not** be matched by `{name: 'John'}`, but 20898 * **will** be matched by `{$: 'John'}`. 20899 * 20900 * - `function(value, index, array)`: A predicate function can be used to write arbitrary filters. 20901 * The function is called for each element of the array, with the element, its index, and 20902 * the entire array itself as arguments. 20903 * 20904 * The final result is an array of those elements that the predicate returned true for. 20905 * 20906 * @param {function(actual, expected)|true|false} [comparator] Comparator which is used in 20907 * determining if values retrieved using `expression` (when it is not a function) should be 20908 * considered a match based on the expected value (from the filter expression) and actual 20909 * value (from the object in the array). 20910 * 20911 * Can be one of: 20912 * 20913 * - `function(actual, expected)`: 20914 * The function will be given the object value and the predicate value to compare and 20915 * should return true if both values should be considered equal. 20916 * 20917 * - `true`: A shorthand for `function(actual, expected) { return angular.equals(actual, expected)}`. 20918 * This is essentially strict comparison of expected and actual. 20919 * 20920 * - `false`: A short hand for a function which will look for a substring match in a case 20921 * insensitive way. Primitive values are converted to strings. Objects are not compared against 20922 * primitives, unless they have a custom `toString` method (e.g. `Date` objects). 20923 * 20924 * 20925 * Defaults to `false`. 20926 * 20927 * @param {string} [anyPropertyKey] The special property name that matches against any property. 20928 * By default `$`. 20929 * 20930 * @example 20931 <example name="filter-filter"> 20932 <file name="index.html"> 20933 <div ng-init="friends = [{name:'John', phone:'555-1276'}, 20934 {name:'Mary', phone:'800-BIG-MARY'}, 20935 {name:'Mike', phone:'555-4321'}, 20936 {name:'Adam', phone:'555-5678'}, 20937 {name:'Julie', phone:'555-8765'}, 20938 {name:'Juliette', phone:'555-5678'}]"></div> 20939 20940 <label>Search: <input ng-model="searchText"></label> 20941 <table id="searchTextResults"> 20942 <tr><th>Name</th><th>Phone</th></tr> 20943 <tr ng-repeat="friend in friends | filter:searchText"> 20944 <td>{{friend.name}}</td> 20945 <td>{{friend.phone}}</td> 20946 </tr> 20947 </table> 20948 <hr> 20949 <label>Any: <input ng-model="search.$"></label> <br> 20950 <label>Name only <input ng-model="search.name"></label><br> 20951 <label>Phone only <input ng-model="search.phone"></label><br> 20952 <label>Equality <input type="checkbox" ng-model="strict"></label><br> 20953 <table id="searchObjResults"> 20954 <tr><th>Name</th><th>Phone</th></tr> 20955 <tr ng-repeat="friendObj in friends | filter:search:strict"> 20956 <td>{{friendObj.name}}</td> 20957 <td>{{friendObj.phone}}</td> 20958 </tr> 20959 </table> 20960 </file> 20961 <file name="protractor.js" type="protractor"> 20962 var expectFriendNames = function(expectedNames, key) { 20963 element.all(by.repeater(key + ' in friends').column(key + '.name')).then(function(arr) { 20964 arr.forEach(function(wd, i) { 20965 expect(wd.getText()).toMatch(expectedNames[i]); 20966 }); 20967 }); 20968 }; 20969 20970 it('should search across all fields when filtering with a string', function() { 20971 var searchText = element(by.model('searchText')); 20972 searchText.clear(); 20973 searchText.sendKeys('m'); 20974 expectFriendNames(['Mary', 'Mike', 'Adam'], 'friend'); 20975 20976 searchText.clear(); 20977 searchText.sendKeys('76'); 20978 expectFriendNames(['John', 'Julie'], 'friend'); 20979 }); 20980 20981 it('should search in specific fields when filtering with a predicate object', function() { 20982 var searchAny = element(by.model('search.$')); 20983 searchAny.clear(); 20984 searchAny.sendKeys('i'); 20985 expectFriendNames(['Mary', 'Mike', 'Julie', 'Juliette'], 'friendObj'); 20986 }); 20987 it('should use a equal comparison when comparator is true', function() { 20988 var searchName = element(by.model('search.name')); 20989 var strict = element(by.model('strict')); 20990 searchName.clear(); 20991 searchName.sendKeys('Julie'); 20992 strict.click(); 20993 expectFriendNames(['Julie'], 'friendObj'); 20994 }); 20995 </file> 20996 </example> 20997 */ 20998 20999function filterFilter() { 21000 return function(array, expression, comparator, anyPropertyKey) { 21001 if (!isArrayLike(array)) { 21002 if (array == null) { 21003 return array; 21004 } else { 21005 throw minErr('filter')('notarray', 'Expected array but received: {0}', array); 21006 } 21007 } 21008 21009 anyPropertyKey = anyPropertyKey || '$'; 21010 var expressionType = getTypeForFilter(expression); 21011 var predicateFn; 21012 var matchAgainstAnyProp; 21013 21014 switch (expressionType) { 21015 case 'function': 21016 predicateFn = expression; 21017 break; 21018 case 'boolean': 21019 case 'null': 21020 case 'number': 21021 case 'string': 21022 matchAgainstAnyProp = true; 21023 // falls through 21024 case 'object': 21025 predicateFn = createPredicateFn(expression, comparator, anyPropertyKey, matchAgainstAnyProp); 21026 break; 21027 default: 21028 return array; 21029 } 21030 21031 return Array.prototype.filter.call(array, predicateFn); 21032 }; 21033} 21034 21035// Helper functions for `filterFilter` 21036function createPredicateFn(expression, comparator, anyPropertyKey, matchAgainstAnyProp) { 21037 var shouldMatchPrimitives = isObject(expression) && (anyPropertyKey in expression); 21038 var predicateFn; 21039 21040 if (comparator === true) { 21041 comparator = equals; 21042 } else if (!isFunction(comparator)) { 21043 comparator = function(actual, expected) { 21044 if (isUndefined(actual)) { 21045 // No substring matching against `undefined` 21046 return false; 21047 } 21048 if ((actual === null) || (expected === null)) { 21049 // No substring matching against `null`; only match against `null` 21050 return actual === expected; 21051 } 21052 if (isObject(expected) || (isObject(actual) && !hasCustomToString(actual))) { 21053 // Should not compare primitives against objects, unless they have custom `toString` method 21054 return false; 21055 } 21056 21057 actual = lowercase('' + actual); 21058 expected = lowercase('' + expected); 21059 return actual.indexOf(expected) !== -1; 21060 }; 21061 } 21062 21063 predicateFn = function(item) { 21064 if (shouldMatchPrimitives && !isObject(item)) { 21065 return deepCompare(item, expression[anyPropertyKey], comparator, anyPropertyKey, false); 21066 } 21067 return deepCompare(item, expression, comparator, anyPropertyKey, matchAgainstAnyProp); 21068 }; 21069 21070 return predicateFn; 21071} 21072 21073function deepCompare(actual, expected, comparator, anyPropertyKey, matchAgainstAnyProp, dontMatchWholeObject) { 21074 var actualType = getTypeForFilter(actual); 21075 var expectedType = getTypeForFilter(expected); 21076 21077 if ((expectedType === 'string') && (expected.charAt(0) === '!')) { 21078 return !deepCompare(actual, expected.substring(1), comparator, anyPropertyKey, matchAgainstAnyProp); 21079 } else if (isArray(actual)) { 21080 // In case `actual` is an array, consider it a match 21081 // if ANY of it's items matches `expected` 21082 return actual.some(function(item) { 21083 return deepCompare(item, expected, comparator, anyPropertyKey, matchAgainstAnyProp); 21084 }); 21085 } 21086 21087 switch (actualType) { 21088 case 'object': 21089 var key; 21090 if (matchAgainstAnyProp) { 21091 for (key in actual) { 21092 // Under certain, rare, circumstances, key may not be a string and `charAt` will be undefined 21093 // See: https://github.com/angular/angular.js/issues/15644 21094 if (key.charAt && (key.charAt(0) !== '$') && 21095 deepCompare(actual[key], expected, comparator, anyPropertyKey, true)) { 21096 return true; 21097 } 21098 } 21099 return dontMatchWholeObject ? false : deepCompare(actual, expected, comparator, anyPropertyKey, false); 21100 } else if (expectedType === 'object') { 21101 for (key in expected) { 21102 var expectedVal = expected[key]; 21103 if (isFunction(expectedVal) || isUndefined(expectedVal)) { 21104 continue; 21105 } 21106 21107 var matchAnyProperty = key === anyPropertyKey; 21108 var actualVal = matchAnyProperty ? actual : actual[key]; 21109 if (!deepCompare(actualVal, expectedVal, comparator, anyPropertyKey, matchAnyProperty, matchAnyProperty)) { 21110 return false; 21111 } 21112 } 21113 return true; 21114 } else { 21115 return comparator(actual, expected); 21116 } 21117 case 'function': 21118 return false; 21119 default: 21120 return comparator(actual, expected); 21121 } 21122} 21123 21124// Used for easily differentiating between `null` and actual `object` 21125function getTypeForFilter(val) { 21126 return (val === null) ? 'null' : typeof val; 21127} 21128 21129var MAX_DIGITS = 22; 21130var DECIMAL_SEP = '.'; 21131var ZERO_CHAR = '0'; 21132 21133/** 21134 * @ngdoc filter 21135 * @name currency 21136 * @kind function 21137 * 21138 * @description 21139 * Formats a number as a currency (ie $1,234.56). When no currency symbol is provided, default 21140 * symbol for current locale is used. 21141 * 21142 * @param {number} amount Input to filter. 21143 * @param {string=} symbol Currency symbol or identifier to be displayed. 21144 * @param {number=} fractionSize Number of decimal places to round the amount to, defaults to default max fraction size for current locale 21145 * @returns {string} Formatted number. 21146 * 21147 * 21148 * @example 21149 <example module="currencyExample" name="currency-filter"> 21150 <file name="index.html"> 21151 <script> 21152 angular.module('currencyExample', []) 21153 .controller('ExampleController', ['$scope', function($scope) { 21154 $scope.amount = 1234.56; 21155 }]); 21156 </script> 21157 <div ng-controller="ExampleController"> 21158 <input type="number" ng-model="amount" aria-label="amount"> <br> 21159 default currency symbol ($): <span id="currency-default">{{amount | currency}}</span><br> 21160 custom currency identifier (USD$): <span id="currency-custom">{{amount | currency:"USD$"}}</span><br> 21161 no fractions (0): <span id="currency-no-fractions">{{amount | currency:"USD$":0}}</span> 21162 </div> 21163 </file> 21164 <file name="protractor.js" type="protractor"> 21165 it('should init with 1234.56', function() { 21166 expect(element(by.id('currency-default')).getText()).toBe('$1,234.56'); 21167 expect(element(by.id('currency-custom')).getText()).toBe('USD$1,234.56'); 21168 expect(element(by.id('currency-no-fractions')).getText()).toBe('USD$1,235'); 21169 }); 21170 it('should update', function() { 21171 if (browser.params.browser === 'safari') { 21172 // Safari does not understand the minus key. See 21173 // https://github.com/angular/protractor/issues/481 21174 return; 21175 } 21176 element(by.model('amount')).clear(); 21177 element(by.model('amount')).sendKeys('-1234'); 21178 expect(element(by.id('currency-default')).getText()).toBe('-$1,234.00'); 21179 expect(element(by.id('currency-custom')).getText()).toBe('-USD$1,234.00'); 21180 expect(element(by.id('currency-no-fractions')).getText()).toBe('-USD$1,234'); 21181 }); 21182 </file> 21183 </example> 21184 */ 21185currencyFilter.$inject = ['$locale']; 21186function currencyFilter($locale) { 21187 var formats = $locale.NUMBER_FORMATS; 21188 return function(amount, currencySymbol, fractionSize) { 21189 if (isUndefined(currencySymbol)) { 21190 currencySymbol = formats.CURRENCY_SYM; 21191 } 21192 21193 if (isUndefined(fractionSize)) { 21194 fractionSize = formats.PATTERNS[1].maxFrac; 21195 } 21196 21197 //
21197if null or undefined pass it through 21198 return (amount == null) 21199 ? amount 21200 : formatNumber(amount, formats.PATTERNS[1], formats.GROUP_SEP, formats.DECIMAL_SEP, fractionSize). 21201 replace(/\u00A4/g
vendor: 30,724 bytes, lines 21201-22033
21201, currencySymbol); 21202 }; 21203} 21204 21205/** 21206 * @ngdoc filter 21207 * @name number 21208 * @kind function 21209 * 21210 * @description 21211 * Formats a number as text. 21212 * 21213 * If the input is null or undefined, it will just be returned. 21214 * If the input is infinite (Infinity or -Infinity), the Infinity symbol '∞' or '-∞' is returned, respectively. 21215 * If the input is not a number an empty string is returned. 21216 * 21217 * 21218 * @param {number|string} number Number to format. 21219 * @param {(number|string)=} fractionSize Number of decimal places to round the number to. 21220 * If this is not provided then the fraction size is computed from the current locale's number 21221 * formatting pattern. In the case of the default locale, it will be 3. 21222 * @returns {string} Number rounded to `fractionSize` appropriately formatted based on the current 21223 * locale (e.g., in the en_US locale it will have "." as the decimal separator and 21224 * include "," group separators after each third digit). 21225 * 21226 * @example 21227 <example module="numberFilterExample" name="number-filter"> 21228 <file name="index.html"> 21229 <script> 21230 angular.module('numberFilterExample', []) 21231 .controller('ExampleController', ['$scope', function($scope) { 21232 $scope.val = 1234.56789; 21233 }]); 21234 </script> 21235 <div ng-controller="ExampleController"> 21236 <label>Enter number: <input ng-model='val'></label><br> 21237 Default formatting: <span id='number-default'>{{val | number}}</span><br> 21238 No fractions: <span>{{val | number:0}}</span><br> 21239 Negative number: <span>{{-val | number:4}}</span> 21240 </div> 21241 </file> 21242 <file name="protractor.js" type="protractor"> 21243 it('should format numbers', function() { 21244 expect(element(by.id('number-default')).getText()).toBe('1,234.568'); 21245 expect(element(by.binding('val | number:0')).getText()).toBe('1,235'); 21246 expect(element(by.binding('-val | number:4')).getText()).toBe('-1,234.5679'); 21247 }); 21248 21249 it('should update', function() { 21250 element(by.model('val')).clear(); 21251 element(by.model('val')).sendKeys('3374.333'); 21252 expect(element(by.id('number-default')).getText()).toBe('3,374.333'); 21253 expect(element(by.binding('val | number:0')).getText()).toBe('3,374'); 21254 expect(element(by.binding('-val | number:4')).getText()).toBe('-3,374.3330'); 21255 }); 21256 </file> 21257 </example> 21258 */ 21259numberFilter.$inject = ['$locale']; 21260function numberFilter($locale) { 21261 var formats = $locale.NUMBER_FORMATS; 21262 return function(number, fractionSize) { 21263 21264 // if null or undefined pass it through 21265 return (number == null) 21266 ? number 21267 : formatNumber(number, formats.PATTERNS[0], formats.GROUP_SEP, formats.DECIMAL_SEP, 21268 fractionSize); 21269 }; 21270} 21271 21272/** 21273 * Parse a number (as a string) into three components that can be used 21274 * for formatting the number. 21275 * 21276 * (Significant bits of this parse algorithm came from https://github.com/MikeMcl/big.js/) 21277 * 21278 * @param {string} numStr The number to parse 21279 * @return {object} An object describing this number, containing the following keys: 21280 * - d : an array of digits containing leading zeros as necessary 21281 * - i : the number of the digits in `d` that are to the left of the decimal point 21282 * - e : the exponent for numbers that would need more than `MAX_DIGITS` digits in `d` 21283 * 21284 */ 21285function parse(numStr) { 21286 var exponent = 0, digits, numberOfIntegerDigits; 21287 var i, j, zeros; 21288 21289 // Decimal point? 21290 if ((numberOfIntegerDigits = numStr.indexOf(DECIMAL_SEP)) > -1) { 21291 numStr = numStr.replace(DECIMAL_SEP, ''); 21292 } 21293 21294 // Exponential form? 21295 if ((i = numStr.search(/e/i)) > 0) { 21296 // Work out the exponent. 21297 if (numberOfIntegerDigits < 0) numberOfIntegerDigits = i; 21298 numberOfIntegerDigits += +numStr.slice(i + 1); 21299 numStr = numStr.substring(0, i); 21300 } else if (numberOfIntegerDigits < 0) { 21301 // There was no decimal point or exponent so it is an integer. 21302 numberOfIntegerDigits = numStr.length; 21303 } 21304 21305 // Count the number of leading zeros. 21306 for (i = 0; numStr.charAt(i) === ZERO_CHAR; i++) { /* empty */ } 21307 21308 if (i === (zeros = numStr.length)) { 21309 // The digits are all zero. 21310 digits = [0]; 21311 numberOfIntegerDigits = 1; 21312 } else { 21313 // Count the number of trailing zeros 21314 zeros--; 21315 while (numStr.charAt(zeros) === ZERO_CHAR) zeros--; 21316 21317 // Trailing zeros are insignificant so ignore them 21318 numberOfIntegerDigits -= i; 21319 digits = []; 21320 // Convert string to array of digits without leading/trailing zeros. 21321 for (j = 0; i <= zeros; i++, j++) { 21322 digits[j] = +numStr.charAt(i); 21323 } 21324 } 21325 21326 // If the number overflows the maximum allowed digits then use an exponent. 21327 if (numberOfIntegerDigits > MAX_DIGITS) { 21328 digits = digits.splice(0, MAX_DIGITS - 1); 21329 exponent = numberOfIntegerDigits - 1; 21330 numberOfIntegerDigits = 1; 21331 } 21332 21333 return { d: digits, e: exponent, i: numberOfIntegerDigits }; 21334} 21335 21336/** 21337 * Round the parsed number to the specified number of decimal places 21338 * This function changed the parsedNumber in-place 21339 */ 21340function roundNumber(parsedNumber, fractionSize, minFrac, maxFrac) { 21341 var digits = parsedNumber.d; 21342 var fractionLen = digits.length - parsedNumber.i; 21343 21344 // determine fractionSize if it is not specified; `+fractionSize` converts it to a number 21345 fractionSize = (isUndefined(fractionSize)) ? Math.min(Math.max(minFrac, fractionLen), maxFrac) : +fractionSize; 21346 21347 // The index of the digit to where rounding is to occur 21348 var roundAt = fractionSize + parsedNumber.i; 21349 var digit = digits[roundAt]; 21350 21351 if (roundAt > 0) { 21352 // Drop fractional digits beyond `roundAt` 21353 digits.splice(Math.max(parsedNumber.i, roundAt)); 21354 21355 // Set non-fractional digits beyond `roundAt` to 0 21356 for (var j = roundAt; j < digits.length; j++) { 21357 digits[j] = 0; 21358 } 21359 } else { 21360 // We rounded to zero so reset the parsedNumber 21361 fractionLen = Math.max(0, fractionLen); 21362 parsedNumber.i = 1; 21363 digits.length = Math.max(1, roundAt = fractionSize + 1); 21364 digits[0] = 0; 21365 for (var i = 1; i < roundAt; i++) digits[i] = 0; 21366 } 21367 21368 if (digit >= 5) { 21369 if (roundAt - 1 < 0) { 21370 for (var k = 0; k > roundAt; k--) { 21371 digits.unshift(0); 21372 parsedNumber.i++; 21373 } 21374 digits.unshift(1); 21375 parsedNumber.i++; 21376 } else { 21377 digits[roundAt - 1]++; 21378 } 21379 } 21380 21381 // Pad out with zeros to get the required fraction length 21382 for (; fractionLen < Math.max(0, fractionSize); fractionLen++) digits.push(0); 21383 21384 21385 // Do any carrying, e.g. a digit was rounded up to 10 21386 var carry = digits.reduceRight(function(carry, d, i, digits) { 21387 d = d + carry; 21388 digits[i] = d % 10; 21389 return Math.floor(d / 10); 21390 }, 0); 21391 if (carry) { 21392 digits.unshift(carry); 21393 parsedNumber.i++; 21394 } 21395} 21396 21397/** 21398 * Format a number into a string 21399 * @param {number} number The number to format 21400 * @param {{ 21401 * minFrac, // the minimum number of digits required in the fraction part of the number 21402 * maxFrac, // the maximum number of digits required in the fraction part of the number 21403 * gSize, // number of digits in each group of separated digits 21404 * lgSize, // number of digits in the last group of digits before the decimal separator 21405 * negPre, // the string to go in front of a negative number (e.g. `-` or `(`)) 21406 * posPre, // the string to go in front of a positive number 21407 * negSuf, // the string to go after a negative number (e.g. `)`) 21408 * posSuf // the string to go after a positive number 21409 * }} pattern 21410 * @param {string} groupSep The string to separate groups of number (e.g. `,`) 21411 * @param {string} decimalSep The string to act as the decimal separator (e.g. `.`) 21412 * @param {[type]} fractionSize The size of the fractional part of the number 21413 * @return {string} The number formatted as a string 21414 */ 21415function formatNumber(number, pattern, groupSep, decimalSep, fractionSize) { 21416 21417 if (!(isString(number) || isNumber(number)) || isNaN(number)) return ''; 21418 21419 var isInfinity = !isFinite(number); 21420 var isZero = false; 21421 var numStr = Math.abs(number) + '', 21422 formattedText = '', 21423 parsedNumber; 21424 21425 if (isInfinity) { 21426 formattedText = '\u221e'; 21427 } else { 21428 parsedNumber = parse(numStr); 21429 21430 roundNumber(parsedNumber, fractionSize, pattern.minFrac, pattern.maxFrac); 21431 21432 var digits = parsedNumber.d; 21433 var integerLen = parsedNumber.i; 21434 var exponent = parsedNumber.e; 21435 var decimals = []; 21436 isZero = digits.reduce(function(isZero, d) { return isZero && !d; }, true); 21437 21438 // pad zeros for small numbers 21439 while (integerLen < 0) { 21440 digits.unshift(0); 21441 integerLen++; 21442 } 21443 21444 // extract decimals digits 21445 if (integerLen > 0) { 21446 decimals = digits.splice(integerLen, digits.length); 21447 } else { 21448 decimals = digits; 21449 digits = [0]; 21450 } 21451 21452 // format the integer digits with grouping separators 21453 var groups = []; 21454 if (digits.length >= pattern.lgSize) { 21455 groups.unshift(digits.splice(-pattern.lgSize, digits.length).join('')); 21456 } 21457 while (digits.length > pattern.gSize) { 21458 groups.unshift(digits.splice(-pattern.gSize, digits.length).join('')); 21459 } 21460 if (digits.length) { 21461 groups.unshift(digits.join('')); 21462 } 21463 formattedText = groups.join(groupSep); 21464 21465 // append the decimal digits 21466 if (decimals.length) { 21467 formattedText += decimalSep + decimals.join(''); 21468 } 21469 21470 if (exponent) { 21471 formattedText += 'e+' + exponent; 21472 } 21473 } 21474 if (number < 0 && !isZero) { 21475 return pattern.negPre + formattedText + pattern.negSuf; 21476 } else { 21477 return pattern.posPre + formattedText + pattern.posSuf; 21478 } 21479} 21480 21481function padNumber(num, digits, trim, negWrap) { 21482 var neg = ''; 21483 if (num < 0 || (negWrap && num <= 0)) { 21484 if (negWrap) { 21485 num = -num + 1; 21486 } else { 21487 num = -num; 21488 neg = '-'; 21489 } 21490 } 21491 num = '' + num; 21492 while (num.length < digits) num = ZERO_CHAR + num; 21493 if (trim) { 21494 num = num.substr(num.length - digits); 21495 } 21496 return neg + num; 21497} 21498 21499 21500function dateGetter(name, size, offset, trim, negWrap) { 21501 offset = offset || 0; 21502 return function(date) { 21503 var value = date['get' + name](); 21504 if (offset > 0 || value > -offset) { 21505 value += offset; 21506 } 21507 if (value === 0 && offset === -12) value = 12; 21508 return padNumber(value, size, trim, negWrap); 21509 }; 21510} 21511 21512function dateStrGetter(name, shortForm, standAlone) { 21513 return function(date, formats) { 21514 var value = date['get' + name](); 21515 var propPrefix = (standAlone ? 'STANDALONE' : '') + (shortForm ? 'SHORT' : ''); 21516 var get = uppercase(propPrefix + name); 21517 21518 return formats[get][value]; 21519 }; 21520} 21521 21522function timeZoneGetter(date, formats, offset) { 21523 var zone = -1 * offset; 21524 var paddedZone = (zone >= 0) ? '+' : ''; 21525 21526 paddedZone += padNumber(Math[zone > 0 ? 'floor' : 'ceil'](zone / 60), 2) + 21527 padNumber(Math.abs(zone % 60), 2); 21528 21529 return paddedZone; 21530} 21531 21532function getFirstThursdayOfYear(year) { 21533 // 0 = index of January 21534 var dayOfWeekOnFirst = (new Date(year, 0, 1)).getDay(); 21535 // 4 = index of Thursday (+1 to account for 1st = 5) 21536 // 11 = index of *next* Thursday (+1 account for 1st = 12) 21537 return new Date(year, 0, ((dayOfWeekOnFirst <= 4) ? 5 : 12) - dayOfWeekOnFirst); 21538} 21539 21540function getThursdayThisWeek(datetime) { 21541 return new Date(datetime.getFullYear(), datetime.getMonth(), 21542 // 4 = index of Thursday 21543 datetime.getDate() + (4 - datetime.getDay())); 21544} 21545 21546function weekGetter(size) { 21547 return function(date) { 21548 var firstThurs = getFirstThursdayOfYear(date.getFullYear()), 21549 thisThurs = getThursdayThisWeek(date); 21550 21551 var diff = +thisThurs - +firstThurs, 21552 result = 1 + Math.round(diff / 6.048e8); // 6.048e8 ms per week 21553 21554 return padNumber(result, size); 21555 }; 21556} 21557 21558function ampmGetter(date, formats) { 21559 return date.getHours() < 12 ? formats.AMPMS[0] : formats.AMPMS[1]; 21560} 21561 21562function eraGetter(date, formats) { 21563 return date.getFullYear() <= 0 ? formats.ERAS[0] : formats.ERAS[1]; 21564} 21565 21566function longEraGetter(date, formats) { 21567 return date.getFullYear() <= 0 ? formats.ERANAMES[0] : formats.ERANAMES[1]; 21568} 21569 21570var DATE_FORMATS = { 21571 yyyy: dateGetter('FullYear', 4, 0, false, true), 21572 yy: dateGetter('FullYear', 2, 0, true, true), 21573 y: dateGetter('FullYear', 1, 0, false, true), 21574 MMMM: dateStrGetter('Month'), 21575 MMM: dateStrGetter('Month', true), 21576 MM: dateGetter('Month', 2, 1), 21577 M: dateGetter('Month', 1, 1), 21578 LLLL: dateStrGetter('Month', false, true), 21579 dd: dateGetter('Date', 2), 21580 d: dateGetter('Date', 1), 21581 HH: dateGetter('Hours', 2), 21582 H: dateGetter('Hours', 1), 21583 hh: dateGetter('Hours', 2, -12), 21584 h: dateGetter('Hours', 1, -12), 21585 mm: dateGetter('Minutes', 2), 21586 m: dateGetter('Minutes', 1), 21587 ss: dateGetter('Seconds', 2), 21588 s: dateGetter('Seconds', 1), 21589 // while ISO 8601 requires fractions to be prefixed with `.` or `,` 21590 // we can be just safely rely on using `sss` since we currently don't support single or two digit fractions 21591 sss: dateGetter('Milliseconds', 3), 21592 EEEE: dateStrGetter('Day'), 21593 EEE: dateStrGetter('Day', true), 21594 a: ampmGetter, 21595 Z: timeZoneGetter, 21596 ww: weekGetter(2), 21597 w: weekGetter(1), 21598 G: eraGetter, 21599 GG: eraGetter, 21600 GGG: eraGetter, 21601 GGGG: longEraGetter 21602}; 21603 21604var DATE_FORMATS_SPLIT = /((?:[^yMLdHhmsaZEwG']+)|(?:'(?:[^']|'')*')|(?:E+|y+|M+|L+|d+|H+|h+|m+|s+|a|Z|G+|w+))([\s\S]*)/, 21605 NUMBER_STRING = /^-?\d+$/; 21606 21607/** 21608 * @ngdoc filter 21609 * @name date 21610 * @kind function 21611 * 21612 * @description 21613 * Formats `date` to a string based on the requested `format`. 21614 * 21615 * `format` string can be composed of the following elements: 21616 * 21617 * * `'yyyy'`: 4 digit representation of year (e.g. AD 1 => 0001, AD 2010 => 2010) 21618 * * `'yy'`: 2 digit representation of year, padded (00-99). (e.g. AD 2001 => 01, AD 2010 => 10) 21619 * * `'y'`: 1 digit representation of year, e.g. (AD 1 => 1, AD 199 => 199) 21620 * * `'MMMM'`: Month in year (January-December) 21621 * * `'MMM'`: Month in year (Jan-Dec) 21622 * * `'MM'`: Month in year, padded (01-12) 21623 * * `'M'`: Month in year (1-12) 21624 * * `'LLLL'`: Stand-alone month in year (January-December) 21625 * * `'dd'`: Day in month, padded (01-31) 21626 * * `'d'`: Day in month (1-31) 21627 * * `'EEEE'`: Day in Week,(Sunday-Saturday) 21628 * * `'EEE'`: Day in Week, (Sun-Sat) 21629 * * `'HH'`: Hour in day, padded (00-23) 21630 * * `'H'`: Hour in day (0-23) 21631 * * `'hh'`: Hour in AM/PM, padded (01-12) 21632 * * `'h'`: Hour in AM/PM, (1-12) 21633 * * `'mm'`: Minute in hour, padded (00-59) 21634 * * `'m'`: Minute in hour (0-59) 21635 * * `'ss'`: Second in minute, padded (00-59) 21636 * * `'s'`: Second in minute (0-59) 21637 * * `'sss'`: Millisecond in second, padded (000-999) 21638 * * `'a'`: AM/PM marker 21639 * * `'Z'`: 4 digit (+sign) representation of the timezone offset (-1200-+1200) 21640 * * `'ww'`: Week of year, padded (00-53). Week 01 is the week with the first Thursday of the year 21641 * * `'w'`: Week of year (0-53). Week 1 is the week with the first Thursday of the year 21642 * * `'G'`, `'GG'`, `'GGG'`: The abbreviated form of the era string (e.g. 'AD') 21643 * * `'GGGG'`: The long form of the era string (e.g. 'Anno Domini') 21644 * 21645 * `format` string can also be one of the following predefined 21646 * {@link guide/i18n localizable formats}: 21647 * 21648 * * `'medium'`: equivalent to `'MMM d, y h:mm:ss a'` for en_US locale 21649 * (e.g. Sep 3, 2010 12:05:08 PM) 21650 * * `'short'`: equivalent to `'M/d/yy h:mm a'` for en_US locale (e.g. 9/3/10 12:05 PM) 21651 * * `'fullDate'`: equivalent to `'EEEE, MMMM d, y'` for en_US locale 21652 * (e.g. Friday, September 3, 2010) 21653 * * `'longDate'`: equivalent to `'MMMM d, y'` for en_US locale (e.g. September 3, 2010) 21654 * * `'mediumDate'`: equivalent to `'MMM d, y'` for en_US locale (e.g. Sep 3, 2010) 21655 * * `'shortDate'`: equivalent to `'M/d/yy'` for en_US locale (e.g. 9/3/10) 21656 * * `'mediumTime'`: equivalent to `'h:mm:ss a'` for en_US locale (e.g. 12:05:08 PM) 21657 * * `'shortTime'`: equivalent to `'h:mm a'` for en_US locale (e.g. 12:05 PM) 21658 * 21659 * `format` string can contain literal values. These need to be escaped by surrounding with single quotes (e.g. 21660 * `"h 'in the morning'"`). In order to output a single quote, escape it - i.e., two single quotes in a sequence 21661 * (e.g. `"h 'o''clock'"`). 21662 * 21663 * Any other characters in the `format` string will be output as-is. 21664 * 21665 * @param {(Date|number|string)} date Date to format either as Date object, milliseconds (string or 21666 * number) or various ISO 8601 datetime string formats (e.g. yyyy-MM-ddTHH:mm:ss.sssZ and its 21667 * shorter versions like yyyy-MM-ddTHH:mmZ, yyyy-MM-dd or yyyyMMddTHHmmssZ). If no timezone is 21668 * specified in the string input, the time is considered to be in the local timezone. 21669 * @param {string=} format Formatting rules (see Description). If not specified, 21670 * `mediumDate` is used. 21671 * @param {string=} timezone Timezone to be used for formatting. It understands UTC/GMT and the 21672 * continental US time zone abbreviations, but for general use, use a time zone offset, for 21673 * example, `'+0430'` (4 hours, 30 minutes east of the Greenwich meridian) 21674 * If not specified, the timezone of the browser will be used. 21675 * @returns {string} Formatted string or the input if input is not recognized as date/millis. 21676 * 21677 * @example 21678 <example name="filter-date"> 21679 <file name="index.html"> 21680 <span ng-non-bindable>{{1288323623006 | date:'medium'}}</span>: 21681 <span>{{1288323623006 | date:'medium'}}</span><br> 21682 <span ng-non-bindable>{{1288323623006 | date:'yyyy-MM-dd HH:mm:ss Z'}}</span>: 21683 <span>{{1288323623006 | date:'yyyy-MM-dd HH:mm:ss Z'}}</span><br> 21684 <span ng-non-bindable>{{1288323623006 | date:'MM/dd/yyyy @ h:mma'}}</span>: 21685 <span>{{'1288323623006' | date:'MM/dd/yyyy @ h:mma'}}</span><br> 21686 <span ng-non-bindable>{{1288323623006 | date:"MM/dd/yyyy 'at' h:mma"}}</span>: 21687 <span>{{'1288323623006' | date:"MM/dd/yyyy 'at' h:mma"}}</span><br> 21688 </file> 21689 <file name="protractor.js" type="protractor"> 21690 it('should format date', function() { 21691 expect(element(by.binding("1288323623006 | date:'medium'")).getText()). 21692 toMatch(/Oct 2\d, 2010 \d{1,2}:\d{2}:\d{2} (AM|PM)/); 21693 expect(element(by.binding("1288323623006 | date:'yyyy-MM-dd HH:mm:ss Z'")).getText()). 21694 toMatch(/2010-10-2\d \d{2}:\d{2}:\d{2} (-|\+)?\d{4}/); 21695 expect(element(by.binding("'1288323623006' | date:'MM/dd/yyyy @ h:mma'")).getText()). 21696 toMatch(/10\/2\d\/2010 @ \d{1,2}:\d{2}(AM|PM)/); 21697 expect(element(by.binding("'1288323623006' | date:\"MM/dd/yyyy 'at' h:mma\"")).getText()). 21698 toMatch(/10\/2\d\/2010 at \d{1,2}:\d{2}(AM|PM)/); 21699 }); 21700 </file> 21701 </example> 21702 */ 21703dateFilter.$inject = ['$locale']; 21704function dateFilter($locale) { 21705 21706 21707 var R_ISO8601_STR = /^(\d{4})-?(\d\d)-?(\d\d)(?:T(\d\d)(?::?(\d\d)(?::?(\d\d)(?:\.(\d+))?)?)?(Z|([+-])(\d\d):?(\d\d))?)?$/; 21708 // 1 2 3 4 5 6 7 8 9 10 11 21709 function jsonStringToDate(string) { 21710 var match; 21711 if ((match = string.match(R_ISO8601_STR))) { 21712 var date = new Date(0), 21713 tzHour = 0, 21714 tzMin = 0, 21715 dateSetter = match[8] ? date.setUTCFullYear : date.setFullYear, 21716 timeSetter = match[8] ? date.setUTCHours : date.setHours; 21717 21718 if (match[9]) { 21719 tzHour = toInt(match[9] + match[10]); 21720 tzMin = toInt(match[9] + match[11]); 21721 } 21722 dateSetter.call(date, toInt(match[1]), toInt(match[2]) - 1, toInt(match[3])); 21723 var h = toInt(match[4] || 0) - tzHour; 21724 var m = toInt(match[5] || 0) - tzMin; 21725 var s = toInt(match[6] || 0); 21726 var ms = Math.round(parseFloat('0.' + (match[7] || 0)) * 1000); 21727 timeSetter.call(date, h, m, s, ms); 21728 return date; 21729 } 21730 return string; 21731 } 21732 21733 21734 return function(date, format, timezone) { 21735 var text = '', 21736 parts = [], 21737 fn, match; 21738 21739 format = format || 'mediumDate'; 21740 format = $locale.DATETIME_FORMATS[format] || format; 21741 if (isString(date)) { 21742 date = NUMBER_STRING.test(date) ? toInt(date) : jsonStringToDate(date); 21743 } 21744 21745 if (isNumber(date)) { 21746 date = new Date(date); 21747 } 21748 21749 if (!isDate(date) || !isFinite(date.getTime())) { 21750 return date; 21751 } 21752 21753 while (format) { 21754 match = DATE_FORMATS_SPLIT.exec(format); 21755 if (match) { 21756 parts = concat(parts, match, 1); 21757 format = parts.pop(); 21758 } else { 21759 parts.push(format); 21760 format = null; 21761 } 21762 } 21763 21764 var dateTimezoneOffset = date.getTimezoneOffset(); 21765 if (timezone) { 21766 dateTimezoneOffset = timezoneToOffset(timezone, dateTimezoneOffset); 21767 date = convertTimezoneToLocal(date, timezone, true); 21768 } 21769 forEach(parts, function(value) { 21770 fn = DATE_FORMATS[value]; 21771 text += fn ? fn(date, $locale.DATETIME_FORMATS, dateTimezoneOffset) 21772 : value === '\'\'' ? '\'' : value.replace(/(^'|'$)/g, '').replace(/''/g, '\''); 21773 }); 21774 21775 return text; 21776 }; 21777} 21778 21779 21780/** 21781 * @ngdoc filter 21782 * @name json 21783 * @kind function 21784 * 21785 * @description 21786 * Allows you to convert a JavaScript object into JSON string. 21787 * 21788 * This filter is mostly useful for debugging. When using the double curly {{value}} notation 21789 * the binding is automatically converted to JSON. 21790 * 21791 * @param {*} object Any JavaScript object (including arrays and primitive types) to filter. 21792 * @param {number=} spacing The number of spaces to use per indentation, defaults to 2. 21793 * @returns {string} JSON string. 21794 * 21795 * 21796 * @example 21797 <example name="filter-json"> 21798 <file name="index.html"> 21799 <pre id="default-spacing">{{ {'name':'value'} | json }}</pre> 21800 <pre id="custom-spacing">{{ {'name':'value'} | json:4 }}</pre> 21801 </file> 21802 <file name="protractor.js" type="protractor"> 21803 it('should jsonify filtered objects', function() { 21804 expect(element(by.id('default-spacing')).getText()).toMatch(/\{\n {2}"name": ?"value"\n}/); 21805 expect(element(by.id('custom-spacing')).getText()).toMatch(/\{\n {4}"name": ?"value"\n}/); 21806 }); 21807 </file> 21808 </example> 21809 * 21810 */ 21811function jsonFilter() { 21812 return function(object, spacing) { 21813 if (isUndefined(spacing)) { 21814 spacing = 2; 21815 } 21816 return toJson(object, spacing); 21817 }; 21818} 21819 21820 21821/** 21822 * @ngdoc filter 21823 * @name lowercase 21824 * @kind function 21825 * @description 21826 * Converts string to lowercase. 21827 * 21828 * See the {@link ng.uppercase uppercase filter documentation} for a functionally identical example. 21829 * 21830 * @see angular.lowercase 21831 */ 21832var lowercaseFilter = valueFn(lowercase); 21833 21834 21835/** 21836 * @ngdoc filter 21837 * @name uppercase 21838 * @kind function 21839 * @description 21840 * Converts string to uppercase. 21841 * @example 21842 <example module="uppercaseFilterExample" name="filter-uppercase"> 21843 <file name="index.html"> 21844 <script> 21845 angular.module('uppercaseFilterExample', []) 21846 .controller('ExampleController', ['$scope', function($scope) { 21847 $scope.title = 'This is a title'; 21848 }]); 21849 </script> 21850 <div ng-controller="ExampleController"> 21851 <!-- This title should be formatted normally --> 21852 <h1>{{title}}</h1> 21853 <!-- This title should be capitalized --> 21854 <h1>{{title | uppercase}}</h1> 21855 </div> 21856 </file> 21857 </example> 21858 */ 21859var uppercaseFilter = valueFn(uppercase); 21860 21861/** 21862 * @ngdoc filter 21863 * @name limitTo 21864 * @kind function 21865 * 21866 * @description 21867 * Creates a new array or string containing only a specified number of elements. The elements are 21868 * taken from either the beginning or the end of the source array, string or number, as specified by 21869 * the value and sign (positive or negative) of `limit`. Other array-like objects are also supported 21870 * (e.g. array subclasses, NodeLists, jqLite/jQuery collections etc). If a number is used as input, 21871 * it is converted to a string. 21872 * 21873 * @param {Array|ArrayLike|string|number} input - Array/array-like, string or number to be limited. 21874 * @param {string|number} limit - The length of the returned array or string. If the `limit` number 21875 * is positive, `limit` number of items from the beginning of the source array/string are copied. 21876 * If the number is negative, `limit` number of items from the end of the source array/string 21877 * are copied. The `limit` will be trimmed if it exceeds `array.length`. If `limit` is undefined, 21878 * the input will be returned unchanged. 21879 * @param {(string|number)=} begin - Index at which to begin limitation. As a negative index, 21880 * `begin` indicates an offset from the end of `input`. Defaults to `0`. 21881 * @returns {Array|string} A new sub-array or substring of length `limit` or less if the input had 21882 * less than `limit` elements. 21883 * 21884 * @example 21885 <example module="limitToExample" name="limit-to-filter"> 21886 <file name="index.html"> 21887 <script> 21888 angular.module('limitToExample', []) 21889 .controller('ExampleController', ['$scope', function($scope) { 21890 $scope.numbers = [1,2,3,4,5,6,7,8,9]; 21891 $scope.letters = "abcdefghi"; 21892 $scope.longNumber = 2345432342; 21893 $scope.numLimit = 3; 21894 $scope.letterLimit = 3; 21895 $scope.longNumberLimit = 3; 21896 }]); 21897 </script> 21898 <div ng-controller="ExampleController"> 21899 <label> 21900 Limit {{numbers}} to: 21901 <input type="number" step="1" ng-model="numLimit"> 21902 </label> 21903 <p>Output numbers: {{ numbers | limitTo:numLimit }}</p> 21904 <label> 21905 Limit {{letters}} to: 21906 <input type="number" step="1" ng-model="letterLimit"> 21907 </label> 21908 <p>Output letters: {{ letters | limitTo:letterLimit }}</p> 21909 <label> 21910 Limit {{longNumber}} to: 21911 <input type="number" step="1" ng-model="longNumberLimit"> 21912 </label> 21913 <p>Output long number: {{ longNumber | limitTo:longNumberLimit }}</p> 21914 </div> 21915 </file> 21916 <file name="protractor.js" type="protractor"> 21917 var numLimitInput = element(by.model('numLimit')); 21918 var letterLimitInput = element(by.model('letterLimit')); 21919 var longNumberLimitInput = element(by.model('longNumberLimit')); 21920 var limitedNumbers = element(by.binding('numbers | limitTo:numLimit')); 21921 var limitedLetters = element(by.binding('letters | limitTo:letterLimit')); 21922 var limitedLongNumber = element(by.binding('longNumber | limitTo:longNumberLimit')); 21923 21924 it('should limit the number array to first three items', function() { 21925 expect(numLimitInput.getAttribute('value')).toBe('3'); 21926 expect(letterLimitInput.getAttribute('value')).toBe('3'); 21927 expect(longNumberLimitInput.getAttribute('value')).toBe('3'); 21928 expect(limitedNumbers.getText()).toEqual('Output numbers: [1,2,3]'); 21929 expect(limitedLetters.getText()).toEqual('Output letters: abc'); 21930 expect(limitedLongNumber.getText()).toEqual('Output long number: 234'); 21931 }); 21932 21933 // There is a bug in safari and protractor that doesn't like the minus key 21934 // it('should update the output when -3 is entered', function() { 21935 // numLimitInput.clear(); 21936 // numLimitInput.sendKeys('-3'); 21937 // letterLimitInput.clear(); 21938 // letterLimitInput.sendKeys('-3'); 21939 // longNumberLimitInput.clear(); 21940 // longNumberLimitInput.sendKeys('-3'); 21941 // expect(limitedNumbers.getText()).toEqual('Output numbers: [7,8,9]'); 21942 // expect(limitedLetters.getText()).toEqual('Output letters: ghi'); 21943 // expect(limitedLongNumber.getText()).toEqual('Output long number: 342'); 21944 // }); 21945 21946 it('should not exceed the maximum size of input array', function() { 21947 numLimitInput.clear(); 21948 numLimitInput.sendKeys('100'); 21949 letterLimitInput.clear(); 21950 letterLimitInput.sendKeys('100'); 21951 longNumberLimitInput.clear(); 21952 longNumberLimitInput.sendKeys('100'); 21953 expect(limitedNumbers.getText()).toEqual('Output numbers: [1,2,3,4,5,6,7,8,9]'); 21954 expect(limitedLetters.getText()).toEqual('Output letters: abcdefghi'); 21955 expect(limitedLongNumber.getText()).toEqual('Output long number: 2345432342'); 21956 }); 21957 </file> 21958 </example> 21959*/ 21960function limitToFilter() { 21961 return function(input, limit, begin) { 21962 if (Math.abs(Number(limit)) === Infinity) { 21963 limit = Number(limit); 21964 } else { 21965 limit = toInt(limit); 21966 } 21967 if (isNumberNaN(limit)) return input; 21968 21969 if (isNumber(input)) input = input.toString(); 21970 if (!isArrayLike(input)) return input; 21971 21972 begin = (!begin || isNaN(begin)) ? 0 : toInt(begin); 21973 begin = (begin < 0) ? Math.max(0, input.length + begin) : begin; 21974 21975 if (limit >= 0) { 21976 return sliceFn(input, begin, begin + limit); 21977 } else { 21978 if (begin === 0) { 21979 return sliceFn(input, limit, input.length); 21980 } else { 21981 return sliceFn(input, Math.max(0, begin + limit), begin); 21982 } 21983 } 21984 }; 21985} 21986 21987function sliceFn(input, begin, end) { 21988 if (isString(input)) return input.slice(begin, end); 21989 21990 return slice.call(input, begin, end); 21991} 21992 21993/** 21994 * @ngdoc filter 21995 * @name orderBy 21996 * @kind function 21997 * 21998 * @description 21999 * Returns an array containing the items from the specified `collection`, ordered by a `comparator` 22000 * function based on the values computed using the `expression` predicate. 22001 * 22002 * For example, `[{id: 'foo'}, {id: 'bar'}] | orderBy:'id'` would result in 22003 * `[{id: 'bar'}, {id: 'foo'}]`. 22004 * 22005 * The `collection` can be an Array or array-like object (e.g. NodeList, jQuery object, TypedArray, 22006 * String, etc). 22007 * 22008 * The `expression` can be a single predicate, or a list of predicates each serving as a tie-breaker 22009 * for the preceding one. The `expression` is evaluated against each item and the output is used 22010 * for comparing with other items. 22011 * 22012 * You can change the sorting order by setting `reverse` to `true`. By default, items are sorted in 22013 * ascending order. 22014 * 22015 * The comparison is done using the `comparator` function. If none is specified, a default, built-in 22016 * comparator is used (see below for details - in a nutshell, it compares numbers numerically and 22017 * strings alphabetically). 22018 * 22019 * ### Under the hood 22020 * 22021 * Ordering the specified `collection` happens in two phases: 22022 * 22023 * 1. All items are passed through the predicate (or predicates), and the returned values are saved 22024 * along with their type (`string`, `number` etc). For example, an item `{label: 'foo'}`, passed 22025 * through a predicate that extracts the value of the `label` property, would be transformed to: 22026 * ``` 22027 * { 22028 * value: 'foo', 22029 * type: 'string', 22030 * index: ... 22031 * } 22032 * ``` 22033 *
220332. The comparator function is used to sort the items, based on the derived values, types and 22034 * indices. 22035 * 22036 * If you use a custom comparator, it will be called with pairs of objects of the form 22037 * `{value: ..., type: '...', index: ...}` and is expected to return `0` if the objects are equal 22038 * (as far as the comparator is concerned), `-1` if the 1st one should be ranked higher than the 22039 * second, or `1` otherwise. 22040 * 22041 * In order to ensure that the sorting will be deterministic across platforms, if none of the 22042 * specified predicates can distinguish between two items, `orderBy` will automatically introduce a 22043 * dummy predicate that returns the item's index as `value`. 22044 * (If you are using a custom comparator, make sure it can handle this predicate as well.) 22045 * 22046 * If a custom comparator still can't distinguish between two items, then they will be sorted based 22047 * on their index using the built-in comparator. 22048 * 22049 * Finally, in an attempt to simplify things, if a predicate returns an object as the extracted 22050 * value for an item, `orderBy` will try to convert that object to a primitive value, before passing 22051 * it to the comparator. The following rules govern the conversion: 22052 * 22053 * 1. If the object has a `valueOf()` method that returns a primitive, its return value will be 22054 * used instead.<br /> 22055 * (If the object has a `valueOf()` method that returns another object, then the returned object 22056 * will be used in subsequent steps.) 22057 * 2. If the object has a custom `toString()` method (i.e. not the one inherited from `Object`) that 22058 * returns a primitive, its return value will be used instead.<br /> 22059 * (If the object has a `toString()` method that returns another object, then the returned object 22060 * will be used in subsequent steps.) 22061 * 3. No conversion; the object itself is used. 22062 * 22063 * ### The default comparator 22064 * 22065 * The default, built-in comparator should be sufficient for most usecases. In short, it compares 22066 * numbers numerically, strings alphabetically (and case-insensitively), for objects falls back to 22067 * using their index in the original collection, and sorts values of different types by type. 22068 * 22069 * More specifically, it follows these steps to determine the relative order of items: 22070 * 22071 * 1. If the compared values are of different types, compare the types themselves alphabetically. 22072 * 2. If both values are of type `string`, compare them alphabetically in a case- and 22073 * locale-insensitive way. 22074 * 3. If both values are objects, compare their indices instead. 22075 * 4. Otherwise, return: 22076 * - `0`, if the values are equal (by strict equality comparison, i.e. using `===`). 22077 * - `-1`, if the 1st value is "less than" the 2nd value (compared using the `<` operator). 22078 * - `1`, otherwise. 22079 * 22080 * **Note:** If you notice numbers not being sorted as expected, make sure they are actually being 22081 * saved as numbers and not strings. 22082 * **Note:** For the purpose of sorting, `null` values are treated as the string `'null'` (i.e. 22083 * `type: 'string'`, `value: 'null'`). This may cause unexpected sort order relative to 22084 * other values. 22085 * 22086 * @param {Array|ArrayLike} collection - The collection (array or array-like object) to sort. 22087 * @param {(Function|string|Array.<Function|string>)=} expression - A predicate (or list of 22088 * predicates) to be used by the comparator to determine the order of elements. 22089 * 22090 * Can be one of: 22091 * 22092 * - `Function`: A getter function. This function will be called with each item as argument and 22093 * the return value will be used for sorting. 22094 * - `string`: An Angular
vendor: 20,726 bytes, lines 22094-22651
22094 expression. This expression will be evaluated against each item and the 22095 * result will be used for sorting. For example, use `'label'` to sort by a property called 22096 * `label` or `'label.substring(0, 3)'` to sort by the first 3 characters of the `label` 22097 * property.<br /> 22098 * (The result of a constant expression is interpreted as a property name to be used for 22099 * comparison. For example, use `'"special name"'` (note the extra pair of quotes) to sort by a 22100 * property called `special name`.)<br /> 22101 * An expression can be optionally prefixed with `+` or `-` to control the sorting direction, 22102 * ascending or descending. For example, `'+label'` or `'-label'`. If no property is provided, 22103 * (e.g. `'+'` or `'-'`), the collection element itself is used in comparisons. 22104 * - `Array`: An array of function and/or string predicates. If a predicate cannot determine the 22105 * relative order of two items, the next predicate is used as a tie-breaker. 22106 * 22107 * **Note:** If the predicate is missing or empty then it defaults to `'+'`. 22108 * 22109 * @param {boolean=} reverse - If `true`, reverse the sorting order. 22110 * @param {(Function)=} comparator - The comparator function used to determine the relative order of 22111 * value pairs. If omitted, the built-in comparator will be used. 22112 * 22113 * @returns {Array} - The sorted array. 22114 * 22115 * 22116 * @example 22117 * ### Ordering a table with `ngRepeat` 22118 * 22119 * The example below demonstrates a simple {@link ngRepeat ngRepeat}, where the data is sorted by 22120 * age in descending order (expression is set to `'-age'`). The `comparator` is not set, which means 22121 * it defaults to the built-in comparator. 22122 * 22123 <example name="orderBy-static" module="orderByExample1"> 22124 <file name="index.html"> 22125 <div ng-controller="ExampleController"> 22126 <table class="friends"> 22127 <tr> 22128 <th>Name</th> 22129 <th>Phone Number</th> 22130 <th>Age</th> 22131 </tr> 22132 <tr ng-repeat="friend in friends | orderBy:'-age'"> 22133 <td>{{friend.name}}</td> 22134 <td>{{friend.phone}}</td> 22135 <td>{{friend.age}}</td> 22136 </tr> 22137 </table> 22138 </div> 22139 </file> 22140 <file name="script.js"> 22141 angular.module('orderByExample1', []) 22142 .controller('ExampleController', ['$scope', function($scope) { 22143 $scope.friends = [ 22144 {name: 'John', phone: '555-1212', age: 10}, 22145 {name: 'Mary', phone: '555-9876', age: 19}, 22146 {name: 'Mike', phone: '555-4321', age: 21}, 22147 {name: 'Adam', phone: '555-5678', age: 35}, 22148 {name: 'Julie', phone: '555-8765', age: 29} 22149 ]; 22150 }]); 22151 </file> 22152 <file name="style.css"> 22153 .friends { 22154 border-collapse: collapse; 22155 } 22156 22157 .friends th { 22158 border-bottom: 1px solid; 22159 } 22160 .friends td, .friends th { 22161 border-left: 1px solid; 22162 padding: 5px 10px; 22163 } 22164 .friends td:first-child, .friends th:first-child { 22165 border-left: none; 22166 } 22167 </file> 22168 <file name="protractor.js" type="protractor"> 22169 // Element locators 22170 var names = element.all(by.repeater('friends').column('friend.name')); 22171 22172 it('should sort friends by age in reverse order', function() { 22173 expect(names.get(0).getText()).toBe('Adam'); 22174 expect(names.get(1).getText()).toBe('Julie'); 22175 expect(names.get(2).getText()).toBe('Mike'); 22176 expect(names.get(3).getText()).toBe('Mary'); 22177 expect(names.get(4).getText()).toBe('John'); 22178 }); 22179 </file> 22180 </example> 22181 * <hr /> 22182 * 22183 * @example 22184 * ### Changing parameters dynamically 22185 * 22186 * All parameters can be changed dynamically. The next example shows how you can make the columns of 22187 * a table sortable, by binding the `expression` and `reverse` parameters to scope properties. 22188 * 22189 <example name="orderBy-dynamic" module="orderByExample2"> 22190 <file name="index.html"> 22191 <div ng-controller="ExampleController"> 22192 <pre>Sort by = {{propertyName}}; reverse = {{reverse}}</pre> 22193 <hr/> 22194 <button ng-click="propertyName = null; reverse = false">Set to unsorted</button> 22195 <hr/> 22196 <table class="friends"> 22197 <tr> 22198 <th> 22199 <button ng-click="sortBy('name')">Name</button> 22200 <span class="sortorder" ng-show="propertyName === 'name'" ng-class="{reverse: reverse}"></span> 22201 </th> 22202 <th> 22203 <button ng-click="sortBy('phone')">Phone Number</button> 22204 <span class="sortorder" ng-show="propertyName === 'phone'" ng-class="{reverse: reverse}"></span> 22205 </th> 22206 <th> 22207 <button ng-click="sortBy('age')">Age</button> 22208 <span class="sortorder" ng-show="propertyName === 'age'" ng-class="{reverse: reverse}"></span> 22209 </th> 22210 </tr> 22211 <tr ng-repeat="friend in friends | orderBy:propertyName:reverse"> 22212 <td>{{friend.name}}</td> 22213 <td>{{friend.phone}}</td> 22214 <td>{{friend.age}}</td> 22215 </tr> 22216 </table> 22217 </div> 22218 </file> 22219 <file name="script.js"> 22220 angular.module('orderByExample2', []) 22221 .controller('ExampleController', ['$scope', function($scope) { 22222 var friends = [ 22223 {name: 'John', phone: '555-1212', age: 10}, 22224 {name: 'Mary', phone: '555-9876', age: 19}, 22225 {name: 'Mike', phone: '555-4321', age: 21}, 22226 {name: 'Adam', phone: '555-5678', age: 35}, 22227 {name: 'Julie', phone: '555-8765', age: 29} 22228 ]; 22229 22230 $scope.propertyName = 'age'; 22231 $scope.reverse = true; 22232 $scope.friends = friends; 22233 22234 $scope.sortBy = function(propertyName) { 22235 $scope.reverse = ($scope.propertyName === propertyName) ? !$scope.reverse : false; 22236 $scope.propertyName = propertyName; 22237 }; 22238 }]); 22239 </file> 22240 <file name="style.css"> 22241 .friends { 22242 border-collapse: collapse; 22243 } 22244 22245 .friends th { 22246 border-bottom: 1px solid; 22247 } 22248 .friends td, .friends th { 22249 border-left: 1px solid; 22250 padding: 5px 10px; 22251 } 22252 .friends td:first-child, .friends th:first-child { 22253 border-left: none; 22254 } 22255 22256 .sortorder:after { 22257 content: '\25b2'; // BLACK UP-POINTING TRIANGLE 22258 } 22259 .sortorder.reverse:after { 22260 content: '\25bc'; // BLACK DOWN-POINTING TRIANGLE 22261 } 22262 </file> 22263 <file name="protractor.js" type="protractor"> 22264 // Element locators 22265 var unsortButton = element(by.partialButtonText('unsorted')); 22266 var nameHeader = element(by.partialButtonText('Name')); 22267 var phoneHeader = element(by.partialButtonText('Phone')); 22268 var ageHeader = element(by.partialButtonText('Age')); 22269 var firstName = element(by.repeater('friends').column('friend.name').row(0)); 22270 var lastName = element(by.repeater('friends').column('friend.name').row(4)); 22271 22272 it('should sort friends by some property, when clicking on the column header', function() { 22273 expect(firstName.getText()).toBe('Adam'); 22274 expect(lastName.getText()).toBe('John'); 22275 22276 phoneHeader.click(); 22277 expect(firstName.getText()).toBe('John'); 22278 expect(lastName.getText()).toBe('Mary'); 22279 22280 nameHeader.click(); 22281 expect(firstName.getText()).toBe('Adam'); 22282 expect(lastName.getText()).toBe('Mike'); 22283 22284 ageHeader.click(); 22285 expect(firstName.getText()).toBe('John'); 22286 expect(lastName.getText()).toBe('Adam'); 22287 }); 22288 22289 it('should sort friends in reverse order, when clicking on the same column', function() { 22290 expect(firstName.getText()).toBe('Adam'); 22291 expect(lastName.getText()).toBe('John'); 22292 22293 ageHeader.click(); 22294 expect(firstName.getText()).toBe('John'); 22295 expect(lastName.getText()).toBe('Adam'); 22296 22297 ageHeader.click(); 22298 expect(firstName.getText()).toBe('Adam'); 22299 expect(lastName.getText()).toBe('John'); 22300 }); 22301 22302 it('should restore the original order, when clicking "Set to unsorted"', function() { 22303 expect(firstName.getText()).toBe('Adam'); 22304 expect(lastName.getText()).toBe('John'); 22305 22306 unsortButton.click(); 22307 expect(firstName.getText()).toBe('John'); 22308 expect(lastName.getText()).toBe('Julie'); 22309 }); 22310 </file> 22311 </example> 22312 * <hr /> 22313 * 22314 * @example 22315 * ### Using `orderBy` inside a controller 22316 * 22317 * It is also possible to call the `orderBy` filter manually, by injecting `orderByFilter`, and 22318 * calling it with the desired parameters. (Alternatively, you could inject the `$filter` factory 22319 * and retrieve the `orderBy` filter with `$filter('orderBy')`.) 22320 * 22321 <example name="orderBy-call-manually" module="orderByExample3"> 22322 <file name="index.html"> 22323 <div ng-controller="ExampleController"> 22324 <pre>Sort by = {{propertyName}}; reverse = {{reverse}}</pre> 22325 <hr/> 22326 <button ng-click="sortBy(null)">Set to unsorted</button> 22327 <hr/> 22328 <table class="friends"> 22329 <tr> 22330 <th> 22331 <button ng-click="sortBy('name')">Name</button> 22332 <span class="sortorder" ng-show="propertyName === 'name'" ng-class="{reverse: reverse}"></span> 22333 </th> 22334 <th> 22335 <button ng-click="sortBy('phone')">Phone Number</button> 22336 <span class="sortorder" ng-show="propertyName === 'phone'" ng-class="{reverse: reverse}"></span> 22337 </th> 22338 <th> 22339 <button ng-click="sortBy('age')">Age</button> 22340 <span class="sortorder" ng-show="propertyName === 'age'" ng-class="{reverse: reverse}"></span> 22341 </th> 22342 </tr> 22343 <tr ng-repeat="friend in friends"> 22344 <td>{{friend.name}}</td> 22345 <td>{{friend.phone}}</td> 22346 <td>{{friend.age}}</td> 22347 </tr> 22348 </table> 22349 </div> 22350 </file> 22351 <file name="script.js"> 22352 angular.module('orderByExample3', []) 22353 .controller('ExampleController', ['$scope', 'orderByFilter', function($scope, orderBy) { 22354 var friends = [ 22355 {name: 'John', phone: '555-1212', age: 10}, 22356 {name: 'Mary', phone: '555-9876', age: 19}, 22357 {name: 'Mike', phone: '555-4321', age: 21}, 22358 {name: 'Adam', phone: '555-5678', age: 35}, 22359 {name: 'Julie', phone: '555-8765', age: 29} 22360 ]; 22361 22362 $scope.propertyName = 'age'; 22363 $scope.reverse = true; 22364 $scope.friends = orderBy(friends, $scope.propertyName, $scope.reverse); 22365 22366 $scope.sortBy = function(propertyName) { 22367 $scope.reverse = (propertyName !== null && $scope.propertyName === propertyName) 22368 ? !$scope.reverse : false; 22369 $scope.propertyName = propertyName; 22370 $scope.friends = orderBy(friends, $scope.propertyName, $scope.reverse); 22371 }; 22372 }]); 22373 </file> 22374 <file name="style.css"> 22375 .friends { 22376 border-collapse: collapse; 22377 } 22378 22379 .friends th { 22380 border-bottom: 1px solid; 22381 } 22382 .friends td, .friends th { 22383 border-left: 1px solid; 22384 padding: 5px 10px; 22385 } 22386 .friends td:first-child, .friends th:first-child { 22387 border-left: none; 22388 } 22389 22390 .sortorder:after { 22391 content: '\25b2'; // BLACK UP-POINTING TRIANGLE 22392 } 22393 .sortorder.reverse:after { 22394 content: '\25bc'; // BLACK DOWN-POINTING TRIANGLE 22395 } 22396 </file> 22397 <file name="protractor.js" type="protractor"> 22398 // Element locators 22399 var unsortButton = element(by.partialButtonText('unsorted')); 22400 var nameHeader = element(by.partialButtonText('Name')); 22401 var phoneHeader = element(by.partialButtonText('Phone')); 22402 var ageHeader = element(by.partialButtonText('Age')); 22403 var firstName = element(by.repeater('friends').column('friend.name').row(0)); 22404 var lastName = element(by.repeater('friends').column('friend.name').row(4)); 22405 22406 it('should sort friends by some property, when clicking on the column header', function() { 22407 expect(firstName.getText()).toBe('Adam'); 22408 expect(lastName.getText()).toBe('John'); 22409 22410 phoneHeader.click(); 22411 expect(firstName.getText()).toBe('John'); 22412 expect(lastName.getText()).toBe('Mary'); 22413 22414 nameHeader.click(); 22415 expect(firstName.getText()).toBe('Adam'); 22416 expect(lastName.getText()).toBe('Mike'); 22417 22418 ageHeader.click(); 22419 expect(firstName.getText()).toBe('John'); 22420 expect(lastName.getText()).toBe('Adam'); 22421 }); 22422 22423 it('should sort friends in reverse order, when clicking on the same column', function() { 22424 expect(firstName.getText()).toBe('Adam'); 22425 expect(lastName.getText()).toBe('John'); 22426 22427 ageHeader.click(); 22428 expect(firstName.getText()).toBe('John'); 22429 expect(lastName.getText()).toBe('Adam'); 22430 22431 ageHeader.click(); 22432 expect(firstName.getText()).toBe('Adam'); 22433 expect(lastName.getText()).toBe('John'); 22434 }); 22435 22436 it('should restore the original order, when clicking "Set to unsorted"', function() { 22437 expect(firstName.getText()).toBe('Adam'); 22438 expect(lastName.getText()).toBe('John'); 22439 22440 unsortButton.click(); 22441 expect(firstName.getText()).toBe('John'); 22442 expect(lastName.getText()).toBe('Julie'); 22443 }); 22444 </file> 22445 </example> 22446 * <hr /> 22447 * 22448 * @example 22449 * ### Using a custom comparator 22450 * 22451 * If you have very specific requirements about the way items are sorted, you can pass your own 22452 * comparator function. For example, you might need to compare some strings in a locale-sensitive 22453 * way. (When specifying a custom comparator, you also need to pass a value for the `reverse` 22454 * argument - passing `false` retains the default sorting order, i.e. ascending.) 22455 * 22456 <example name="orderBy-custom-comparator" module="orderByExample4"> 22457 <file name="index.html"> 22458 <div ng-controller="ExampleController"> 22459 <div class="friends-container custom-comparator"> 22460 <h3>Locale-sensitive Comparator</h3> 22461 <table class="friends"> 22462 <tr> 22463 <th>Name</th> 22464 <th>Favorite Letter</th> 22465 </tr> 22466 <tr ng-repeat="friend in friends | orderBy:'favoriteLetter':false:localeSensitiveComparator"> 22467 <td>{{friend.name}}</td> 22468 <td>{{friend.favoriteLetter}}</td> 22469 </tr> 22470 </table> 22471 </div> 22472 <div class="friends-container default-comparator"> 22473 <h3>Default Comparator</h3> 22474 <table class="friends"> 22475 <tr> 22476 <th>Name</th> 22477 <th>Favorite Letter</th> 22478 </tr> 22479 <tr ng-repeat="friend in friends | orderBy:'favoriteLetter'"> 22480 <td>{{friend.name}}</td> 22481 <td>{{friend.favoriteLetter}}</td> 22482 </tr> 22483 </table> 22484 </div> 22485 </div> 22486 </file> 22487 <file name="script.js"> 22488 angular.module('orderByExample4', []) 22489 .controller('ExampleController', ['$scope', function($scope) { 22490 $scope.friends = [ 22491 {name: 'John', favoriteLetter: 'Ä'}, 22492 {name: 'Mary', favoriteLetter: 'Ü'}, 22493 {name: 'Mike', favoriteLetter: 'Ö'}, 22494 {name: 'Adam', favoriteLetter: 'H'}, 22495 {name: 'Julie', favoriteLetter: 'Z'} 22496 ]; 22497 22498 $scope.localeSensitiveComparator = function(v1, v2) { 22499 // If we don't get strings, just compare by index 22500 if (v1.type !== 'string' || v2.type !== 'string') { 22501 return (v1.index < v2.index) ? -1 : 1; 22502 } 22503 22504 // Compare strings alphabetically, taking locale into account 22505 return v1.value.localeCompare(v2.value); 22506 }; 22507 }]); 22508 </file> 22509 <file name="style.css"> 22510 .friends-container { 22511 display: inline-block; 22512 margin: 0 30px; 22513 } 22514 22515 .friends { 22516 border-collapse: collapse; 22517 } 22518 22519 .friends th { 22520 border-bottom: 1px solid; 22521 } 22522 .friends td, .friends th { 22523 border-left: 1px solid; 22524 padding: 5px 10px; 22525 } 22526 .friends td:first-child, .friends th:first-child { 22527 border-left: none; 22528 } 22529 </file> 22530 <file name="protractor.js" type="protractor"> 22531 // Element locators 22532 var container = element(by.css('.custom-comparator')); 22533 var names = container.all(by.repeater('friends').column('friend.name')); 22534 22535 it('should sort friends by favorite letter (in correct alphabetical order)', function() { 22536 expect(names.get(0).getText()).toBe('John'); 22537 expect(names.get(1).getText()).toBe('Adam'); 22538 expect(names.get(2).getText()).toBe('Mike'); 22539 expect(names.get(3).getText()).toBe('Mary'); 22540 expect(names.get(4).getText()).toBe('Julie'); 22541 }); 22542 </file> 22543 </example> 22544 * 22545 */ 22546orderByFilter.$inject = ['$parse']; 22547function orderByFilter($parse) { 22548 return function(array, sortPredicate, reverseOrder, compareFn) { 22549 22550 if (array == null) return array; 22551 if (!isArrayLike(array)) { 22552 throw minErr('orderBy')('notarray', 'Expected array but received: {0}', array); 22553 } 22554 22555 if (!isArray(sortPredicate)) { sortPredicate = [sortPredicate]; } 22556 if (sortPredicate.length === 0) { sortPredicate = ['+']; } 22557 22558 var predicates = processPredicates(sortPredicate); 22559 22560 var descending = reverseOrder ? -1 : 1; 22561 22562 // Define the `compare()` function. Use a default comparator if none is specified. 22563 var compare = isFunction(compareFn) ? compareFn : defaultCompare; 22564 22565 // The next three lines are a version of a Swartzian Transform idiom from Perl 22566 // (sometimes called the Decorate-Sort-Undecorate idiom) 22567 // See https://en.wikipedia.org/wiki/Schwartzian_transform 22568 var compareValues = Array.prototype.map.call(array, getComparisonObject); 22569 compareValues.sort(doComparison); 22570 array = compareValues.map(function(item) { return item.value; }); 22571 22572 return array; 22573 22574 function getComparisonObject(value, index) { 22575 // NOTE: We are adding an extra `tieBreaker` value based on the element's index. 22576 // This will be used to keep the sort stable when none of the input predicates can 22577 // distinguish between two elements. 22578 return { 22579 value: value, 22580 tieBreaker: {value: index, type: 'number', index: index}, 22581 predicateValues: predicates.map(function(predicate) { 22582 return getPredicateValue(predicate.get(value), index); 22583 }) 22584 }; 22585 } 22586 22587 function doComparison(v1, v2) { 22588 for (var i = 0, ii = predicates.length; i < ii; i++) { 22589 var result = compare(v1.predicateValues[i], v2.predicateValues[i]); 22590 if (result) { 22591 return result * predicates[i].descending * descending; 22592 } 22593 } 22594 22595 return (compare(v1.tieBreaker, v2.tieBreaker) || defaultCompare(v1.tieBreaker, v2.tieBreaker)) * descending; 22596 } 22597 }; 22598 22599 function processPredicates(sortPredicates) { 22600 return sortPredicates.map(function(predicate) { 22601 var descending = 1, get = identity; 22602 22603 if (isFunction(predicate)) { 22604 get = predicate; 22605 } else if (isString(predicate)) { 22606 if ((predicate.charAt(0) === '+' || predicate.charAt(0) === '-')) { 22607 descending = predicate.charAt(0) === '-' ? -1 : 1; 22608 predicate = predicate.substring(1); 22609 } 22610 if (predicate !== '') { 22611 get = $parse(predicate); 22612 if (get.constant) { 22613 var key = get(); 22614 get = function(value) { return value[key]; }; 22615 } 22616 } 22617 } 22618 return {get: get, descending: descending}; 22619 }); 22620 } 22621 22622 function isPrimitive(value) { 22623 switch (typeof value) { 22624 case 'number': /* falls through */ 22625 case 'boolean': /* falls through */ 22626 case 'string': 22627 return true; 22628 default: 22629 return false; 22630 } 22631 } 22632 22633 function objectValue(value) { 22634 // If `valueOf` is a valid function use that 22635 if (isFunction(value.valueOf)) { 22636 value = value.valueOf(); 22637 if (isPrimitive(value)) return value; 22638 } 22639 // If `toString` is a valid function and not the one from `Object.prototype` use that 22640 if (hasCustomToString(value)) { 22641 value = value.toString(); 22642 if (isPrimitive(value)) return value; 22643 } 22644 22645 return value; 22646 } 22647 22648 function getPredicateValue(value, index) { 22649 var type = typeof value; 22650 if (value === null) { 22651 type = '
vendor: 3,900 bytes, lines 22651-22774
22651string'; 22652 value = 'null'; 22653 } else if (type === 'object') { 22654 value = objectValue(value); 22655 } 22656 return {value: value, type: type, index: index}; 22657 } 22658 22659 function defaultCompare(v1, v2) { 22660 var result = 0; 22661 var type1 = v1.type; 22662 var type2 = v2.type; 22663 22664 if (type1 === type2) { 22665 var value1 = v1.value; 22666 var value2 = v2.value; 22667 22668 if (type1 === 'string') { 22669 // Compare strings case-insensitively 22670 value1 = value1.toLowerCase(); 22671 value2 = value2.toLowerCase(); 22672 } else if (type1 === 'object') { 22673 // For basic objects, use the position of the object 22674 // in the collection instead of the value 22675 if (isObject(value1)) value1 = v1.index; 22676 if (isObject(value2)) value2 = v2.index; 22677 } 22678 22679 if (value1 !== value2) { 22680 result = value1 < value2 ? -1 : 1; 22681 } 22682 } else { 22683 result = type1 < type2 ? -1 : 1; 22684 } 22685 22686 return result; 22687 } 22688} 22689 22690function ngDirective(directive) { 22691 if (isFunction(directive)) { 22692 directive = { 22693 link: directive 22694 }; 22695 } 22696 directive.restrict = directive.restrict || 'AC'; 22697 return valueFn(directive); 22698} 22699 22700/** 22701 * @ngdoc directive 22702 * @name a 22703 * @restrict E 22704 * 22705 * @description 22706 * Modifies the default behavior of the html a tag so that the default action is prevented when 22707 * the href attribute is empty. 22708 * 22709 * For dynamically creating `href` attributes for a tags, see the {@link ng.ngHref `ngHref`} directive. 22710 */ 22711var htmlAnchorDirective = valueFn({ 22712 restrict: 'E', 22713 compile: function(element, attr) { 22714 if (!attr.href && !attr.xlinkHref) { 22715 return function(scope, element) { 22716 // If the linked element is not an anchor tag anymore, do nothing 22717 if (element[0].nodeName.toLowerCase() !== 'a') return; 22718 22719 // SVGAElement does not use the href attribute, but rather the 'xlinkHref' attribute. 22720 var href = toString.call(element.prop('href')) === '[object SVGAnimatedString]' ? 22721 'xlink:href' : 'href'; 22722 element.on('click', function(event) { 22723 // if we have no href url, then don't navigate anywhere. 22724 if (!element.attr(href)) { 22725 event.preventDefault(); 22726 } 22727 }); 22728 }; 22729 } 22730 } 22731}); 22732 22733/** 22734 * @ngdoc directive 22735 * @name ngHref 22736 * @restrict A 22737 * @priority 99 22738 * 22739 * @description 22740 * Using Angular markup like `{{hash}}` in an href attribute will 22741 * make the link go to the wrong URL if the user clicks it before 22742 * Angular has a chance to replace the `{{hash}}` markup with its 22743 * value. Until Angular replaces the markup the link will be broken 22744 * and will most likely return a 404 error. The `ngHref` directive 22745 * solves this problem. 22746 * 22747 * The wrong way to write it: 22748 * ```html 22749 * <a href="http://www.gravatar.com/avatar/{{hash}}">link1</a> 22750 * ``` 22751 * 22752 * The correct way to write it: 22753 * ```html 22754 * <a ng-href="http://www.gravatar.com/avatar/{{hash}}">link1</a> 22755 * ``` 22756 * 22757 * @element A 22758 * @param {template} ngHref any string which can contain `{{}}` markup. 22759 * 22760 * @example 22761 * This example shows various combinations of `href`, `ng-href` and `ng-click` attributes 22762 * in links and their different behaviors: 22763 <example name="ng-href"> 22764 <file name="index.html"> 22765 <input ng-model="value" /><br /> 22766 <a id="link-1" href ng-click="value = 1">link 1</a> (link, don't reload)<br /> 22767 <a id="link-2" href="" ng-click="value = 2">link 2</a> (link, don't reload)<br /> 22768 <a id="link-3" ng-href="/{{'123'}}">link 3</a> (link, reload!)<br /> 22769 <a id="link-4" href="" name="xx" ng-click="value = 4">anchor</a> (link, don't reload)<br /> 22770 <a id="link-5" name="xxx" ng-click="value = 5">anchor</a> (no link)<br /> 22771 <a id="link-6" ng-href="{{value}}">link</a> (link, change location) 22772 </file> 22773 <file name="protractor.js" type="protractor"> 22774 it('should execute ng-click but not reload when href without value', function() {
22775 element(by.id('link-1')).click(); 22776 expect(element(by.model('value')).getAttribute('value')).toEqual('1'); 22777 expect(element(by.id('link-1')).getAttribute('href')).toBe(''); 22778 }); 22779 22780 it('should execute ng-click but not reload when href empty string', function() { 22781 element(by.id('link-2')).click(); 22782 expect(element(by.model('value')).getAttribute('value')).toEqual('2'); 22783 expect(element(by.id('link-2')).getAttribute('href')).toBe(''); 22784 }); 22785 22786 it('should execute ng-click and change url when ng-href specified', function() { 22787 expect(element(by.id('link-3')).getAttribute('href')).toMatch(/\/123$/); 22788 22789 element(by.id('link-3')).click(); 22790 22791 // At this point, we navigate away from an Angular page, so we need 22792 // to use browser.driver to get the base webdriver. 22793 22794 browser.wait(function() { 22795 return browser.driver.getCurrentUrl().then(function(url) { 22796 return url.match(/\/123$/); 22797 }); 22798 }, 5000, 'page should navigate to /123'); 22799 }); 22800 22801 it('should execute ng-click but not reload when href empty string and name specified', function() { 22802 element(by.id('link-4')).click(); 22803 expect(element(by.model('value')).getAttribute('value')).toEqual('4'); 22804 expect(element(by.id('link-4')).getAttribute('href')).toBe(''); 22805 }); 22806 22807 it('should execute ng-click but not reload when no href but name specified', function() { 22808 element(by.id('link-5')).click(); 22809 expect(element(by.model('value')).getAttribute('value')).toEqual('5'); 22810 expect(element(by.id('link-5')).getAttribute('href')).toBe(null); 22811 }); 22812 22813 it('should only change url when only ng-href', function() { 22814 element(by.model('value')).clear(); 22815 element(by.model('value')).sendKeys('6'); 22816 expect(element(by.id('link-6')).getAttribute('href')).toMatch(/\/6$/); 22817 22818 element(by.id('link-6')).click(); 22819 22820 // At this point, we navigate away from an Angular page, so we need 22821 // to use browser.driver to get the base webdriver. 22822 browser.wait(function() { 22823 return browser.driver.getCurrentUrl().then(function(url) { 22824 return url.match(/\/6$/); 22825 }); 22826 }, 5000, 'page should navigate to /6'); 22827 }); 22828 </file> 22829 </example> 22830 */ 22831 22832/** 22833 * @ngdoc directive 22834 * @name ngSrc 22835 * @restrict A 22836 * @priority 99 22837 * 22838 * @description 22839 * Using Angular markup like `{{hash}}` in a `src` attribute doesn't 22840 * work right: The browser will fetch from the URL with the literal 22841 * text `{{hash}}` until Angular replaces the expression inside 22842 * `{{hash}}`. The `ngSrc` directive solves this problem. 22843 * 22844 * The buggy way to write it: 22845 * ```html 22846 * <img src="http://www.gravatar.com/avatar/{{hash}}" alt="Description"/> 22847 * ``` 22848 * 22849 * The correct way to write it: 22850 * ```html 22851 * <img ng-src="http://www.gravatar.com/avatar/{{hash}}" alt="Description" /> 22852 * ``` 22853 * 22854 * @element IMG 22855 * @param {template} ngSrc any string which can contain `{{}}` markup. 22856 */ 22857 22858/** 22859 * @ngdoc directive 22860 * @name ngSrcset 22861 * @restrict A 22862 * @priority 99 22863 * 22864 * @description 22865 * Using Angular markup like `{{hash}}` in a `srcset` attribute doesn't 22866 * work right: The browser will fetch from the URL with the literal 22867 * text `{{hash}}` until Angular replaces the expression inside 22868 * `{{hash}}`. The `ngSrcset` directive solves this problem. 22869 * 22870 * The buggy way to write it: 22871 * ```html 22872 * <img srcset="http://www.gravatar.com/avatar/{{hash}} 2x" alt="Description"/> 22873 * ``` 22874 * 22875 * The correct way to write it: 22876 * ```html 22877 * <img ng-srcset="http://www.gravatar.com/avatar/{{hash}} 2x" alt="Description" /> 22878 * ``` 22879 * 22880 * @element IMG 22881 * @param {template} ngSrcset any string which can contain `{{}}` markup. 22882 */ 22883 22884/** 22885 * @ngdoc directive 22886 * @name ngDisabled 22887 * @restrict A 22888 * @priority 100 22889 * 22890 * @description 22891 * 22892 * This directive sets the `disabled` attribute on the element (typically a form control, 22893 * e.g. `input`, `button`, `select` etc.) if the 22894 * {@link guide/expression expression} inside `ngDisabled` evaluates to truthy. 22895 * 22896 * A special directive is necessary because we cannot use interpolation inside the `disabled` 22897 * attribute. See the {@link guide/interpolation interpolation guide} for more info. 22898 * 22899 * @example 22900 <example name="ng-disabled"> 22901 <file name="index.html"> 22902 <label>Click me to toggle: <input type="checkbox" ng-model="checked"></label><br/> 22903 <button ng-model="button" ng-disabled="checked">Button</button> 22904 </file> 22905 <file name="protractor.js" type="protractor"> 22906 it('should toggle button', function() { 22907 expect(element(by.css('button')).getAttribute('disabled')).toBeFalsy();
22908 element(by.model('checked')).click(); 22909 expect(element(by.css('button')).getAttribute('disabled')).toBeTruthy(); 22910 }); 22911 </file> 22912 </example> 22913 * 22914 * @element INPUT 22915 * @param {expression} ngDisabled If the {@link guide/expression expression} is truthy, 22916 * then the `disabled` attribute will be set on the element 22917 */ 22918 22919 22920/** 22921 * @ngdoc directive 22922 * @name ngChecked 22923 * @restrict A 22924 * @priority 100 22925 * 22926 * @description 22927 * Sets the `checked` attribute on the element, if the expression inside `ngChecked` is truthy. 22928 * 22929 * Note that this directive should not be used together with {@link ngModel `ngModel`}, 22930 * as this can lead to unexpected behavior. 22931 * 22932 * A special directive is necessary because we cannot use interpolation inside the `checked` 22933 * attribute. See the {@link guide/interpolation interpolation guide} for more info. 22934 * 22935 * @example 22936 <example name="ng-checked"> 22937 <file name="index.html"> 22938 <label>Check me to check both: <input type="checkbox" ng-model="master"></label><br/> 22939 <input id="checkSlave" type="checkbox" ng-checked="master" aria-label="Slave input"> 22940 </file> 22941 <file name="protractor.js" type="protractor"> 22942 it('should check both checkBoxes', function() { 22943 expect(element(by.id('checkSlave')).getAttribute('checked')).toBeFalsy(); 22944 element(by.model('master')).click(); 22945 expect(element(by.id('checkSlave')).getAttribute('checked')).toBeTruthy(); 22946 }); 22947 </file> 22948 </example> 22949 * 22950 * @element INPUT 22951 * @param {expression} ngChecked If the {@link guide/expression expression} is truthy, 22952 * then the `checked` attribute will be set on the element 22953 */ 22954 22955 22956/** 22957 * @ngdoc directive 22958 * @name ngReadonly 22959 * @restrict A 22960 * @priority 100 22961 * 22962 * @description 22963 * 22964 * Sets the `readonly` attribute on the element, if the expression inside `ngReadonly` is truthy. 22965 * Note that `readonly` applies only to `input` elements with specific types. [See the input docs on 22966 * MDN](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input#attr-readonly) for more information. 22967 * 22968 * A special directive is necessary because we cannot use interpolation inside the `readonly` 22969 * attribute. See the {@link guide/interpolation interpolation guide} for more info. 22970 * 22971 * @example 22972 <example name="ng-readonly"> 22973 <file name="index.html"> 22974 <label>Check me to make text readonly: <input type="checkbox" ng-model="checked"></label><br/> 22975 <input type="text" ng-readonly="checked" value="I'm Angular" aria-label="Readonly field" /> 22976 </file> 22977 <file name="protractor.js" type="protractor"> 22978 it('should toggle readonly attr', function() { 22979 expect(element(by.css('[type="text"]')).getAttribute('readonly')).toBeFalsy(); 22980 element(by.model('checked')).click(); 22981 expect(element(by.css('[type="text"]')).getAttribute('readonly')).toBeTruthy(); 22982 }); 22983 </file> 22984 </example> 22985 * 22986 * @element INPUT 22987 * @param {expression} ngReadonly If the {@link guide/expression expression} is truthy, 22988 * then special attribute "readonly" will be set on the element 22989 */ 22990 22991 22992/** 22993 * @ngdoc directive 22994 * @name ngSelected 22995 * @restrict A 22996 * @priority 100 22997 * 22998 * @description 22999 * 23000 * Sets the `selected` attribute on the element, if the expression inside `ngSelected` is truthy. 23001 * 23002 * A special directive is necessary because we cannot use interpolation inside the `selected` 23003 * attribute. See the {@link guide/interpolation interpolation guide} for more info. 23004 * 23005 * <div class="alert alert-warning"> 23006 * **Note:** `ngSelected` does not interact with the `select` and `ngModel` directives, it only 23007 * sets the `selected` attribute on the element. If you are using `ngModel` on the select, you 23008 * should not use `ngSelected` on the options, as `ngModel` will set the select value and 23009 * selected options. 23010 * </div> 23011 * 23012 * @example 23013 <example name="ng-selected"> 23014 <file name="index.html"> 23015 <label>Check me to select: <input type="checkbox" ng-model="selected"></label><br/> 23016 <select aria-label="ngSelected demo"> 23017 <option>Hello!</option> 23018 <option id="greet" ng-selected="selected">Greetings!</option> 23019 </select> 23020 </file> 23021 <file name="protractor.js" type="protractor"> 23022 it('should select Greetings!', function() { 23023 expect(element(by.id('greet')).getAttribute('selected')).toBeFalsy();
vendor: 16,519 bytes, lines 23024-23518
23024 element(by.model('selected')).click(); 23025 expect(element(by.id('greet')).getAttribute('selected')).toBeTruthy(); 23026 }); 23027 </file> 23028 </example> 23029 * 23030 * @element OPTION 23031 * @param {expression} ngSelected If the {@link guide/expression expression} is truthy, 23032 * then special attribute "selected" will be set on the element 23033 */ 23034 23035/** 23036 * @ngdoc directive 23037 * @name ngOpen 23038 * @restrict A 23039 * @priority 100 23040 * 23041 * @description 23042 * 23043 * Sets the `open` attribute on the element, if the expression inside `ngOpen` is truthy. 23044 * 23045 * A special directive is necessary because we cannot use interpolation inside the `open` 23046 * attribute. See the {@link guide/interpolation interpolation guide} for more info. 23047 * 23048 * ## A note about browser compatibility 23049 * 23050 * Internet Explorer and Edge do not support the `details` element, it is 23051 * recommended to use {@link ng.ngShow} and {@link ng.ngHide} instead. 23052 * 23053 * @example 23054 <example name="ng-open"> 23055 <file name="index.html"> 23056 <label>Toggle details: <input type="checkbox" ng-model="open"></label><br/> 23057 <details id="details" ng-open="open"> 23058 <summary>List</summary> 23059 <ul> 23060 <li>Apple</li> 23061 <li>Orange</li> 23062 <li>Durian</li> 23063 </ul> 23064 </details> 23065 </file> 23066 <file name="protractor.js" type="protractor"> 23067 it('should toggle open', function() { 23068 expect(element(by.id('details')).getAttribute('open')).toBeFalsy(); 23069 element(by.model('open')).click(); 23070 expect(element(by.id('details')).getAttribute('open')).toBeTruthy(); 23071 }); 23072 </file> 23073 </example> 23074 * 23075 * @element DETAILS 23076 * @param {expression} ngOpen If the {@link guide/expression expression} is truthy, 23077 * then special attribute "open" will be set on the element 23078 */ 23079 23080var ngAttributeAliasDirectives = {}; 23081 23082// boolean attrs are evaluated 23083forEach(BOOLEAN_ATTR, function(propName, attrName) { 23084 // binding to multiple is not supported 23085 if (propName === 'multiple') return; 23086 23087 function defaultLinkFn(scope, element, attr) { 23088 scope.$watch(attr[normalized], function ngBooleanAttrWatchAction(value) { 23089 attr.$set(attrName, !!value); 23090 }); 23091 } 23092 23093 var normalized = directiveNormalize('ng-' + attrName); 23094 var linkFn = defaultLinkFn; 23095 23096 if (propName === 'checked') { 23097 linkFn = function(scope, element, attr) { 23098 // ensuring ngChecked doesn't interfere with ngModel when both are set on the same input 23099 if (attr.ngModel !== attr[normalized]) { 23100 defaultLinkFn(scope, element, attr); 23101 } 23102 }; 23103 } 23104 23105 ngAttributeAliasDirectives[normalized] = function() { 23106 return { 23107 restrict: 'A', 23108 priority: 100, 23109 link: linkFn 23110 }; 23111 }; 23112}); 23113 23114// aliased input attrs are evaluated 23115forEach(ALIASED_ATTR, function(htmlAttr, ngAttr) { 23116 ngAttributeAliasDirectives[ngAttr] = function() { 23117 return { 23118 priority: 100, 23119 link: function(scope, element, attr) { 23120 //special case ngPattern when a literal regular expression value 23121 //is used as the expression (this way we don't have to watch anything). 23122 if (ngAttr === 'ngPattern' && attr.ngPattern.charAt(0) === '/') { 23123 var match = attr.ngPattern.match(REGEX_STRING_REGEXP); 23124 if (match) { 23125 attr.$set('ngPattern', new RegExp(match[1], match[2])); 23126 return; 23127 } 23128 } 23129 23130 scope.$watch(attr[ngAttr], function ngAttrAliasWatchAction(value) { 23131 attr.$set(ngAttr, value); 23132 }); 23133 } 23134 }; 23135 }; 23136}); 23137 23138// ng-src, ng-srcset, ng-href are interpolated 23139forEach(['src', 'srcset', 'href'], function(attrName) { 23140 var normalized = directiveNormalize('ng-' + attrName); 23141 ngAttributeAliasDirectives[normalized] = function() { 23142 return { 23143 priority: 99, // it needs to run after the attributes are interpolated 23144 link: function(scope, element, attr) { 23145 var propName = attrName, 23146 name = attrName; 23147 23148 if (attrName === 'href' && 23149 toString.call(element.prop('href')) === '[object SVGAnimatedString]') { 23150 name = 'xlinkHref'; 23151 attr.$attr[name] = 'xlink:href'; 23152 propName = null; 23153 } 23154 23155 attr.$observe(normalized, function(value) { 23156 if (!value) { 23157 if (attrName === 'href') { 23158 attr.$set(name, null); 23159 } 23160 return; 23161 } 23162 23163 attr.$set(name, value); 23164 23165 // Support: IE 9-11 only 23166 // On IE, if "ng:src" directive declaration is used and "src" attribute doesn't exist 23167 // then calling element.setAttribute('src', 'foo') doesn't do anything, so we need 23168 // to set the property as well to achieve the desired effect. 23169 // We use attr[attrName] value since $set can sanitize the url. 23170 if (msie && propName) element.prop(propName, attr[name]); 23171 }); 23172 } 23173 }; 23174 }; 23175}); 23176 23177/* global -nullFormCtrl, -PENDING_CLASS, -SUBMITTED_CLASS 23178 */ 23179var nullFormCtrl = { 23180 $addControl: noop, 23181 $$renameControl: nullFormRenameControl, 23182 $removeControl: noop, 23183 $setValidity: noop, 23184 $setDirty: noop, 23185 $setPristine: noop, 23186 $setSubmitted: noop 23187}, 23188PENDING_CLASS = 'ng-pending', 23189SUBMITTED_CLASS = 'ng-submitted'; 23190 23191function nullFormRenameControl(control, name) { 23192 control.$name = name; 23193} 23194 23195/** 23196 * @ngdoc type 23197 * @name form.FormController 23198 * 23199 * @property {boolean} $pristine True if user has not interacted with the form yet. 23200 * @property {boolean} $dirty True if user has already interacted with the form. 23201 * @property {boolean} $valid True if all of the containing forms and controls are valid. 23202 * @property {boolean} $invalid True if at least one containing control or form is invalid. 23203 * @property {boolean} $submitted True if user has submitted the form even if its invalid. 23204 * 23205 * @property {Object} $pending An object hash, containing references to controls or forms with 23206 * pending validators, where: 23207 * 23208 * - keys are validations tokens (error names). 23209 * - values are arrays of controls or forms that have a pending validator for the given error name. 23210 * 23211 * See {@link form.FormController#$error $error} for a list of built-in validation tokens. 23212 * 23213 * @property {Object} $error An object hash, containing references to controls or forms with failing 23214 * validators, where: 23215 * 23216 * - keys are validation tokens (error names), 23217 * - values are arrays of controls or forms that have a failing validator for the given error name. 23218 * 23219 * Built-in validation tokens: 23220 * - `email` 23221 * - `max` 23222 * - `maxlength` 23223 * - `min` 23224 * - `minlength` 23225 * - `number` 23226 * - `pattern` 23227 * - `required` 23228 * - `url` 23229 * - `date` 23230 * - `datetimelocal` 23231 * - `time` 23232 * - `week` 23233 * - `month` 23234 * 23235 * @description 23236 * `FormController` keeps track of all its controls and nested forms as well as the state of them, 23237 * such as being valid/invalid or dirty/pristine. 23238 * 23239 * Each {@link ng.directive:form form} directive creates an instance 23240 * of `FormController`. 23241 * 23242 */ 23243//asks for $scope to fool the BC controller module 23244FormController.$inject = ['$element', '$attrs', '$scope', '$animate', '$interpolate']; 23245function FormController($element, $attrs, $scope, $animate, $interpolate) { 23246 this.$$controls = []; 23247 23248 // init state 23249 this.$error = {}; 23250 this.$$success = {}; 23251 this.$pending = undefined; 23252 this.$name = $interpolate($attrs.name || $attrs.ngForm || '')($scope); 23253 this.$dirty = false; 23254 this.$pristine = true; 23255 this.$valid = true; 23256 this.$invalid = false; 23257 this.$submitted = false; 23258 this.$$parentForm = nullFormCtrl; 23259 23260 this.$$element = $element; 23261 this.$$animate = $animate; 23262 23263 setupValidity(this); 23264} 23265 23266FormController.prototype = { 23267 /** 23268 * @ngdoc method 23269 * @name form.FormController#$rollbackViewValue 23270 * 23271 * @description 23272 * Rollback all form controls pending updates to the `$modelValue`. 23273 * 23274 * Updates may be pending by a debounced event or because the input is waiting for a some future 23275 * event defined in `ng-model-options`. This method is typically needed by the reset button of 23276 * a form that uses `ng-model-options` to pend updates. 23277 */ 23278 $rollbackViewValue: function() { 23279 forEach(this.$$controls, function(control) { 23280 control.$rollbackViewValue(); 23281 }); 23282 }, 23283 23284 /** 23285 * @ngdoc method 23286 * @name form.FormController#$commitViewValue 23287 * 23288 * @description 23289 * Commit all form controls pending updates to the `$modelValue`. 23290 * 23291 * Updates may be pending by a debounced event or because the input is waiting for a some future 23292 * event defined in `ng-model-options`. This method is rarely needed as `NgModelController` 23293 * usually handles calling this in response to input events. 23294 */ 23295 $commitViewValue: function() { 23296 forEach(this.$$controls, function(control) { 23297 control.$commitViewValue(); 23298 }); 23299 }, 23300 23301 /** 23302 * @ngdoc method 23303 * @name form.FormController#$addControl 23304 * @param {object} control control object, either a {@link form.FormController} or an 23305 * {@link ngModel.NgModelController} 23306 * 23307 * @description 23308 * Register a control with the form. Input elements using ngModelController do this automatically 23309 * when they are linked. 23310 * 23311 * Note that the current state of the control will not be reflected on the new parent form. This 23312 * is not an issue with normal use, as freshly compiled and linked controls are in a `$pristine` 23313 * state. 23314 * 23315 * However, if the method is used programmatically, for example by adding dynamically created controls, 23316 * or controls that have been previously removed without destroying their corresponding DOM element, 23317 * it's the developers responsibility to make sure the current state propagates to the parent form. 23318 * 23319 * For example, if an input control is added that is already `$dirty` and has `$error` properties, 23320 * calling `$setDirty()` and `$validate()` afterwards will propagate the state to the parent form. 23321 */ 23322 $addControl: function(control) { 23323 // Breaking change - before, inputs whose name was "hasOwnProperty" were quietly ignored 23324 // and not added to the scope. Now we throw an error. 23325 assertNotHasOwnProperty(control.$name, 'input'); 23326 this.$$controls.push(control); 23327 23328 if (control.$name) { 23329 this[control.$name] = control; 23330 } 23331 23332 control.$$parentForm = this; 23333 }, 23334 23335 // Private API: rename a form control 23336 $$renameControl: function(control, newName) { 23337 var oldName = control.$name; 23338 23339 if (this[oldName] === control) { 23340 delete this[oldName]; 23341 } 23342 this[newName] = control; 23343 control.$name = newName; 23344 }, 23345 23346 /** 23347 * @ngdoc method 23348 * @name form.FormController#$removeControl 23349 * @param {object} control control object, either a {@link form.FormController} or an 23350 * {@link ngModel.NgModelController} 23351 * 23352 * @description 23353 * Deregister a control from the form. 23354 * 23355 * Input elements using ngModelController do this automatically when they are destroyed. 23356 * 23357 * Note that only the removed control's validation state (`$errors`etc.) will be removed from the 23358 * form. `$dirty`, `$submitted` states will not be changed, because the expected behavior can be 23359 * different from case to case. For example, removing the only `$dirty` control from a form may or 23360 * may not mean that the form is still `$dirty`. 23361 */ 23362 $removeControl: function(control) { 23363 if (control.$name && this[control.$name] === control) { 23364 delete this[control.$name]; 23365 } 23366 forEach(this.$pending, function(value, name) { 23367 // eslint-disable-next-line no-invalid-this 23368 this.$setValidity(name, null, control); 23369 }, this); 23370 forEach(this.$error, function(value, name) { 23371 // eslint-disable-next-line no-invalid-this 23372 this.$setValidity(name, null, control); 23373 }, this); 23374 forEach(this.$$success, function(value, name) { 23375 // eslint-disable-next-line no-invalid-this 23376 this.$setValidity(name, null, control); 23377 }, this); 23378 23379 arrayRemove(this.$$controls, control); 23380 control.$$parentForm = nullFormCtrl; 23381 }, 23382 23383 /** 23384 * @ngdoc method 23385 * @name form.FormController#$setDirty 23386 * 23387 * @description 23388 * Sets the form to a dirty state. 23389 * 23390 * This method can be called to add the 'ng-dirty' class and set the form to a dirty 23391 * state (ng-dirty class). This method will also propagate to parent forms. 23392 */ 23393 $setDirty: function() { 23394 this.$$animate.removeClass(this.$$element, PRISTINE_CLASS); 23395 this.$$animate.addClass(this.$$element, DIRTY_CLASS); 23396 this.$dirty = true; 23397 this.$pristine = false; 23398 this.$$parentForm.$setDirty(); 23399 }, 23400 23401 /** 23402 * @ngdoc method 23403 * @name form.FormController#$setPristine 23404 * 23405 * @description 23406 * Sets the form to its pristine state. 23407 * 23408 * This method sets the form's `$pristine` state to true, the `$dirty` state to false, removes 23409 * the `ng-dirty` class and adds the `ng-pristine` class. Additionally, it sets the `$submitted` 23410 * state to false. 23411 * 23412 * This method will also propagate to all the controls contained in this form. 23413 * 23414 * Setting a form back to a pristine state is often useful when we want to 'reuse' a form after 23415 * saving or resetting it. 23416 */ 23417 $setPristine: function() { 23418 this.$$animate.setClass(this.$$element, PRISTINE_CLASS, DIRTY_CLASS + ' ' + SUBMITTED_CLASS); 23419 this.$dirty = false; 23420 this.$pristine = true; 23421 this.$submitted = false; 23422 forEach(this.$$controls, function(control) { 23423 control.$setPristine(); 23424 }); 23425 }, 23426 23427 /** 23428 * @ngdoc method 23429 * @name form.FormController#$setUntouched 23430 * 23431 * @description 23432 * Sets the form to its untouched state. 23433 * 23434 * This method can be called to remove the 'ng-touched' class and set the form controls to their 23435 * untouched state (ng-untouched class). 23436 * 23437 * Setting a form controls back to their untouched state is often useful when setting the form 23438 * back to its pristine state. 23439 */ 23440 $setUntouched: function() { 23441 forEach(this.$$controls, function(control) { 23442 control.$setUntouched(); 23443 }); 23444 }, 23445 23446 /** 23447 * @ngdoc method 23448 * @name form.FormController#$setSubmitted 23449 * 23450 * @description 23451 * Sets the form to its submitted state. 23452 */ 23453 $setSubmitted: function() { 23454 this.$$animate.addClass(this.$$element, SUBMITTED_CLASS); 23455 this.$submitted = true; 23456 this.$$parentForm.$setSubmitted(); 23457 } 23458}; 23459 23460/** 23461 * @ngdoc method 23462 * @name form.FormController#$setValidity 23463 * 23464 * @description 23465 * Change the validity state of the form, and notify the parent form (if any). 23466 * 23467 * Application developers will rarely need to call this method directly. It is used internally, by 23468 * {@link ngModel.NgModelController#$setValidity NgModelController.$setValidity()}, to propagate a 23469 * control's validity state to the parent `FormController`. 23470 * 23471 * @param {string} validationErrorKey Name of the validator. The `validationErrorKey` will be 23472 * assigned to either `$error[validationErrorKey]` or `$pending[validationErrorKey]` (for 23473 * unfulfilled `$asyncValidators`), so that it is available for data-binding. The 23474 * `validationErrorKey` should be in camelCase and will get converted into dash-case for 23475 * class name. Example: `myError` will result in `ng-valid-my-error` and 23476 * `ng-invalid-my-error` classes and can be bound to as `{{ someForm.$error.myError }}`. 23477 * @param {boolean} isValid Whether the current state is valid (true), invalid (false), pending 23478 * (undefined), or skipped (null). Pending is used for unfulfilled `$asyncValidators`. 23479 * Skipped is used by AngularJS when validators do not run because of parse errors and when 23480 * `$asyncValidators` do not run because any of the `$validators` failed. 23481 * @param {NgModelController | FormController} controller - The controller whose validity state is 23482 * triggering the change. 23483 */ 23484addSetValidityMethod({ 23485 clazz: FormController, 23486 set: function(object, property, controller) { 23487 var list = object[property]; 23488 if (!list) { 23489 object[property] = [controller]; 23490 } else { 23491 var index = list.indexOf(controller); 23492 if (index === -1) { 23493 list.push(controller); 23494 } 23495 } 23496 }, 23497 unset: function(object, property, controller) { 23498 var list = object[property]; 23499 if (!list) { 23500 return; 23501 } 23502 arrayRemove(list, controller); 23503 if (list.length === 0) { 23504 delete object[property]; 23505 } 23506 } 23507}); 23508 23509/** 23510 * @ngdoc directive 23511 * @name ngForm 23512 * @restrict EAC 23513 * 23514 * @description 23515 * Nestable alias of {@link ng.directive:form `form`} directive. HTML 23516 * does not allow nesting of form elements. It is useful to nest forms, for example if the validity of a 23517 * sub-group of controls needs to be determined. 23518 *
23519 * Note: the purpose of `ngForm` is to group controls, 23520 * but not to be a replacement for the `<form>` tag with all of its capabilities 23521 * (e.g. posting to the server, ...). 23522 * 23523 * @param {string=} ngForm|name Name of the form. If specified, the form controller will be published into 23524 * related scope, under this name. 23525 * 23526 */ 23527 23528 /** 23529 * @ngdoc directive 23530 * @name form 23531 * @restrict E 23532 * 23533 * @description 23534 * Directive that instantiates 23535 * {@link form.FormController FormController}. 23536 * 23537 * If the `name` attribute is specified, the form controller is published onto the current scope under 23538 * this name. 23539 * 23540 * # Alias: {@link ng.directive:ngForm `ngForm`} 23541 * 23542 * In Angular, forms can be nested. This means that the outer form is valid when all of the child 23543 * forms are valid as well. However, browsers do not allow nesting of `<form>` elements, so 23544 * Angular provides the {@link ng.directive:ngForm `ngForm`} directive, which behaves identically to 23545 * `form` but can be nested. Nested forms can be useful, for example, if the validity of a sub-group 23546 * of controls needs to be determined. 23547 * 23548 * # CSS classes 23549 * - `ng-valid` is set if the form is valid. 23550 * - `ng-invalid` is set if the form is invalid. 23551 * - `ng-pending` is set if the form is pending. 23552 * - `ng-pristine` is set if the form is pristine. 23553 * - `ng-dirty` is set if the form is dirty. 23554 * - `ng-submitted` is set if the form was submitted. 23555 * 23556 * Keep in mind that ngAnimate can detect each of these classes when added and removed. 23557 * 23558 * 23559 * # Submitting a form and preventing the default action 23560 * 23561 * Since the role of forms in client-side Angular applications is different than in classical 23562 * roundtrip apps, it is desirable for the browser not to translate the form submission into a full 23563 * page reload that sends the data to the server. Instead some javascript logic should be triggered 23564 * to handle the form submission in an application-specific way. 23565 * 23566 * For this reason, Angular prevents the default action (form submission to the server) unless the 23567 * `<form>` element has an `action` attribute specified. 23568 * 23569 * You can use one of the following two ways to specify what javascript method should be called when 23570 * a form is submitted: 23571 * 23572 * - {@link ng.directive:ngSubmit ngSubmit} directive on the form element 23573 * - {@link ng.directive:ngClick ngClick} directive on the first 23574 * button or input field of type submit (input[type=submit]) 23575 * 23576 * To prevent double execution of the handler, use only one of the {@link ng.directive:ngSubmit ngSubmit} 23577 * or {@link ng.directive:ngClick ngClick} directives. 23578 * This is because of the following form submission rules in the HTML specification: 23579 * 23580 * - If a form has only one input field then hitting enter in this field triggers form submit 23581 * (`ngSubmit`) 23582 * - if a form has 2+ input fields and no buttons or input[type=submit] then hitting enter 23583 * doesn't trigger submit 23584 * - if a form has one or more input fields and one or more buttons or input[type=submit] then 23585 * hitting enter in any of the input fields will trigger the click handler on the *first* button or 23586 * input[type=submit] (`ngClick`) *and* a submit handler on the enclosing form (`ngSubmit`) 23587 * 23588 * Any pending `ngModelOptions` changes will take place immediately when an enclosing form is 23589 * submitted. Note that `ngClick` events will occur before the model is updated. Use `ngSubmit` 23590 * to have access to the updated model. 23591 * 23592 * ## Animation Hooks 23593 *
vendor: 11,664 bytes, lines 23593-23905
23593 23594 * Animations in ngForm are triggered when any of the associated CSS classes are added and removed. 23595 * These classes are: `.ng-pristine`, `.ng-dirty`, `.ng-invalid` and `.ng-valid` as well as any 23596 * other validations that are performed within the form. Animations in ngForm are similar to how 23597 * they work in ngClass and animations can be hooked into using CSS transitions, keyframes as well 23598 * as JS animations. 23599 * 23600 * The following example shows a simple way to utilize CSS transitions to style a form element 23601 * that has been rendered as invalid after it has been validated: 23602 * 23603 * <pre> 23604 * //be sure to include ngAnimate as a module to hook into more 23605 * //advanced animations 23606 * .my-form { 23607 * transition:0.5s linear all; 23608 * background: white; 23609 * } 23610 * .my-form.ng-invalid { 23611 * background: red; 23612 * color:white; 23613 * } 23614 * </pre> 23615 * 23616 * @example 23617 <example name="ng-form" deps="angular-animate.js" animations="true" fixBase="true" module="formExample"> 23618 <file name="index.html"> 23619 <script> 23620 angular.module('formExample', []) 23621 .controller('FormController', ['$scope', function($scope) { 23622 $scope.userType = 'guest'; 23623 }]); 23624 </script> 23625 <style> 23626 .my-form { 23627 transition:all linear 0.5s; 23628 background: transparent; 23629 } 23630 .my-form.ng-invalid { 23631 background: red; 23632 } 23633 </style> 23634 <form name="myForm" ng-controller="FormController" class="my-form"> 23635 userType: <input name="input" ng-model="userType" required> 23636 <span class="error" ng-show="myForm.input.$error.required">Required!</span><br> 23637 <code>userType = {{userType}}</code><br> 23638 <code>myForm.input.$valid = {{myForm.input.$valid}}</code><br> 23639 <code>myForm.input.$error = {{myForm.input.$error}}</code><br> 23640 <code>myForm.$valid = {{myForm.$valid}}</code><br> 23641 <code>myForm.$error.required = {{!!myForm.$error.required}}</code><br> 23642 </form> 23643 </file> 23644 <file name="protractor.js" type="protractor"> 23645 it('should initialize to model', function() { 23646 var userType = element(by.binding('userType')); 23647 var valid = element(by.binding('myForm.input.$valid')); 23648 23649 expect(userType.getText()).toContain('guest'); 23650 expect(valid.getText()).toContain('true'); 23651 }); 23652 23653 it('should be invalid if empty', function() { 23654 var userType = element(by.binding('userType')); 23655 var valid = element(by.binding('myForm.input.$valid')); 23656 var userInput = element(by.model('userType')); 23657 23658 userInput.clear(); 23659 userInput.sendKeys(''); 23660 23661 expect(userType.getText()).toEqual('userType ='); 23662 expect(valid.getText()).toContain('false'); 23663 }); 23664 </file> 23665 </example> 23666 * 23667 * @param {string=} name Name of the form. If specified, the form controller will be published into 23668 * related scope, under this name. 23669 */ 23670var formDirectiveFactory = function(isNgForm) { 23671 return ['$timeout', '$parse', function($timeout, $parse) { 23672 var formDirective = { 23673 name: 'form', 23674 restrict: isNgForm ? 'EAC' : 'E', 23675 require: ['form', '^^?form'], //first is the form's own ctrl, second is an optional parent form 23676 controller: FormController, 23677 compile: function ngFormCompile(formElement, attr) { 23678 // Setup initial state of the control 23679 formElement.addClass(PRISTINE_CLASS).addClass(VALID_CLASS); 23680 23681 var nameAttr = attr.name ? 'name' : (isNgForm && attr.ngForm ? 'ngForm' : false); 23682 23683 return { 23684 pre: function ngFormPreLink(scope, formElement, attr, ctrls) { 23685 var controller = ctrls[0]; 23686 23687 // if `action` attr is not present on the form, prevent the default action (submission) 23688 if (!('action' in attr)) { 23689 // we can't use jq events because if a form is destroyed during submission the default 23690 // action is not prevented. see #1238 23691 // 23692 // IE 9 is not affected because it doesn't fire a submit event and try to do a full 23693 // page reload if the form was destroyed by submission of the form via a click handler 23694 // on a button in the form. Looks like an IE9 specific bug. 23695 var handleFormSubmission = function(event) { 23696 scope.$apply(function() { 23697 controller.$commitViewValue(); 23698 controller.$setSubmitted(); 23699 }); 23700 23701 event.preventDefault(); 23702 }; 23703 23704 formElement[0].addEventListener('submit', handleFormSubmission); 23705 23706 // unregister the preventDefault listener so that we don't not leak memory but in a 23707 // way that will achieve the prevention of the default action. 23708 formElement.on('$destroy', function() { 23709 $timeout(function() { 23710 formElement[0].removeEventListener('submit', handleFormSubmission); 23711 }, 0, false); 23712 }); 23713 } 23714 23715 var parentFormCtrl = ctrls[1] || controller.$$parentForm; 23716 parentFormCtrl.$addControl(controller); 23717 23718 var setter = nameAttr ? getSetter(controller.$name) : noop; 23719 23720 if (nameAttr) { 23721 setter(scope, controller); 23722 attr.$observe(nameAttr, function(newValue) { 23723 if (controller.$name === newValue) return; 23724 setter(scope, undefined); 23725 controller.$$parentForm.$$renameControl(controller, newValue); 23726 setter = getSetter(controller.$name); 23727 setter(scope, controller); 23728 }); 23729 } 23730 formElement.on('$destroy', function() { 23731 controller.$$parentForm.$removeControl(controller); 23732 setter(scope, undefined); 23733 extend(controller, nullFormCtrl); //stop propagating child destruction handlers upwards 23734 }); 23735 } 23736 }; 23737 } 23738 }; 23739 23740 return formDirective; 23741 23742 function getSetter(expression) { 23743 if (expression === '') { 23744 //create an assignable expression, so forms with an empty name can be renamed later 23745 return $parse('this[""]').assign; 23746 } 23747 return $parse(expression).assign || noop; 23748 } 23749 }]; 23750}; 23751 23752var formDirective = formDirectiveFactory(); 23753var ngFormDirective = formDirectiveFactory(true); 23754 23755 23756 23757// helper methods 23758function setupValidity(instance) { 23759 instance.$$classCache = {}; 23760 instance.$$classCache[INVALID_CLASS] = !(instance.$$classCache[VALID_CLASS] = instance.$$element.hasClass(VALID_CLASS)); 23761} 23762function addSetValidityMethod(context) { 23763 var clazz = context.clazz, 23764 set = context.set, 23765 unset = context.unset; 23766 23767 clazz.prototype.$setValidity = function(validationErrorKey, state, controller) { 23768 if (isUndefined(state)) { 23769 createAndSet(this, '$pending', validationErrorKey, controller); 23770 } else { 23771 unsetAndCleanup(this, '$pending', validationErrorKey, controller); 23772 } 23773 if (!isBoolean(state)) { 23774 unset(this.$error, validationErrorKey, controller); 23775 unset(this.$$success, validationErrorKey, controller); 23776 } else { 23777 if (state) { 23778 unset(this.$error, validationErrorKey, controller); 23779 set(this.$$success, validationErrorKey, controller); 23780 } else { 23781 set(this.$error, validationErrorKey, controller); 23782 unset(this.$$success, validationErrorKey, controller); 23783 } 23784 } 23785 if (this.$pending) { 23786 cachedToggleClass(this, PENDING_CLASS, true); 23787 this.$valid = this.$invalid = undefined; 23788 toggleValidationCss(this, '', null); 23789 } else { 23790 cachedToggleClass(this, PENDING_CLASS, false); 23791 this.$valid = isObjectEmpty(this.$error); 23792 this.$invalid = !this.$valid; 23793 toggleValidationCss(this, '', this.$valid); 23794 } 23795 23796 // re-read the state as the set/unset methods could have 23797 // combined state in this.$error[validationError] (used for forms), 23798 // where setting/unsetting only increments/decrements the value, 23799 // and does not replace it. 23800 var combinedState; 23801 if (this.$pending && this.$pending[validationErrorKey]) { 23802 combinedState = undefined; 23803 } else if (this.$error[validationErrorKey]) { 23804 combinedState = false; 23805 } else if (this.$$success[validationErrorKey]) { 23806 combinedState = true; 23807 } else { 23808 combinedState = null; 23809 } 23810 23811 toggleValidationCss(this, validationErrorKey, combinedState); 23812 this.$$parentForm.$setValidity(validationErrorKey, combinedState, this); 23813 }; 23814 23815 function createAndSet(ctrl, name, value, controller) { 23816 if (!ctrl[name]) { 23817 ctrl[name] = {}; 23818 } 23819 set(ctrl[name], value, controller); 23820 } 23821 23822 function unsetAndCleanup(ctrl, name, value, controller) { 23823 if (ctrl[name]) { 23824 unset(ctrl[name], value, controller); 23825 } 23826 if (isObjectEmpty(ctrl[name])) { 23827 ctrl[name] = undefined; 23828 } 23829 } 23830 23831 function cachedToggleClass(ctrl, className, switchValue) { 23832 if (switchValue && !ctrl.$$classCache[className]) { 23833 ctrl.$$animate.addClass(ctrl.$$element, className); 23834 ctrl.$$classCache[className] = true; 23835 } else if (!switchValue && ctrl.$$classCache[className]) { 23836 ctrl.$$animate.removeClass(ctrl.$$element, className); 23837 ctrl.$$classCache[className] = false; 23838 } 23839 } 23840 23841 function toggleValidationCss(ctrl, validationErrorKey, isValid) { 23842 validationErrorKey = validationErrorKey ? '-' + snake_case(validationErrorKey, '-') : ''; 23843 23844 cachedToggleClass(ctrl, VALID_CLASS + validationErrorKey, isValid === true); 23845 cachedToggleClass(ctrl, INVALID_CLASS + validationErrorKey, isValid === false); 23846 } 23847} 23848 23849function isObjectEmpty(obj) { 23850 if (obj) { 23851 for (var prop in obj) { 23852 if (obj.hasOwnProperty(prop)) { 23853 return false; 23854 } 23855 } 23856 } 23857 return true; 23858} 23859 23860/* global 23861 VALID_CLASS: false, 23862 INVALID_CLASS: false, 23863 PRISTINE_CLASS: false, 23864 DIRTY_CLASS: false, 23865 ngModelMinErr: false 23866*/ 23867 23868// Regex code was initially obtained from SO prior to modification: https://stackoverflow.com/questions/3143070/javascript-regex-iso-datetime#answer-3143231 23869var 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)$/; 23870// See valid URLs in RFC3987 (http://tools.ietf.org/html/rfc3987) 23871// Note: We are being more lenient, because browsers are too. 23872// 1. Scheme 23873// 2. Slashes 23874// 3. Username 23875// 4. Password 23876// 5. Hostname 23877// 6. Port 23878// 7. Path 23879// 8. Query 23880// 9. Fragment 23881// 1111111111111111 222 333333 44444 55555555555555555555555 666 77777777 8888888 999 23882var URL_REGEXP = /^[a-z][a-z\d.+-]*:\/*(?:[^:@]+(?::[^@]+)?@)?(?:[^\s:/?#]+|\[[a-f\d:]+])(?::\d+)?(?:\/[^?#]*)?(?:\?[^#]*)?(?:#.*)?$/i; 23883// eslint-disable-next-line max-len 23884var 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])?)*$/; 23885var NUMBER_REGEXP = /^\s*(-|\+)?(\d+|(\d*(\.\d*)))([eE][+-]?\d+)?\s*$/; 23886var DATE_REGEXP = /^(\d{4,})-(\d{2})-(\d{2})$/; 23887var DATETIMELOCAL_REGEXP = /^(\d{4,})-(\d\d)-(\d\d)T(\d\d):(\d\d)(?::(\d\d)(\.\d{1,3})?)?$/; 23888var WEEK_REGEXP = /^(\d{4,})-W(\d\d)$/; 23889var MONTH_REGEXP = /^(\d{4,})-(\d\d)$/; 23890var TIME_REGEXP = /^(\d\d):(\d\d)(?::(\d\d)(\.\d{1,3})?)?$/; 23891 23892var PARTIAL_VALIDATION_EVENTS = 'keydown wheel mousedown'; 23893var PARTIAL_VALIDATION_TYPES = createMap(); 23894forEach('date,datetime-local,month,time,week'.split(','), function(type) { 23895 PARTIAL_VALIDATION_TYPES[type] = true; 23896}); 23897 23898var inputType = { 23899 23900 /** 23901 * @ngdoc input 23902 * @name input[text] 23903 * 23904 * @description 23905 * Standard HTML text input with
23905angular data binding, inherited by most of the `input` elements. 23906 * 23907 * 23908 * @param {string} ngModel Assignable angular expression to data-bind to. 23909 * @param {string=} name Property name of the form under which the control is published. 23910 * @param {string=} required Adds `required` validation error key if the value is not entered. 23911 * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to 23912 * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of 23913 * `required` when you want to data-bind to the `required` attribute. 23914 * @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than 23915 * minlength. 23916 * @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than 23917 * maxlength. Setting the attribute to a negative or non-numeric value, allows view values of 23918 * any length. 23919 * @param {string=} pattern Similar to `ngPattern` except that the attribute value is the actual string 23920 * that contains the regular expression body that will be converted to a regular expression 23921 * as in the ngPattern directive. 23922 * @param {string=} ngPattern Sets `pattern` validation error key if the ngModel {@link ngModel.NgModelController#$viewValue $viewValue} 23923 * does not match a RegExp found by evaluating the Angular expression given in the attribute value. 23924 * If the expression evaluates to a RegExp object, then this is used directly. 23925 * If the expression evaluates to a string, then it will be converted to a RegExp 23926 * after wrapping it in `^` and `$` characters. For instance, `"abc"` will be converted to 23927 * `new RegExp('^abc$')`.<br /> 23928 * **Note:** Avoid using the `g` flag on the RegExp, as it will cause each successive search to 23929 * start at the index of the last search's match, thus not taking the whole input value into 23930 * account. 23931 * @param {string=} ngChange Angular expression to be executed when input changes due to user 23932 * interaction with the input element. 23933 * @param {boolean=} [ngTrim=true] If set to false Angular will not automatically trim the input. 23934 * This parameter is ignored for input[type=password] controls, which will never trim the 23935 * input. 23936 * 23937 * @example 23938 <example name="text-input-directive" module="textInputExample"> 23939 <file name="index.html"> 23940 <script> 23941 angular.module('textInputExample', []) 23942 .controller('ExampleController', ['$scope', function($scope) { 23943 $scope.example = { 23944 text: 'guest', 23945 word: /^\s*\w*\s*$/ 23946 }; 23947 }]); 23948 </script>
23949 <form name="myForm" ng-controller="ExampleController"> 23950 <label>Single word: 23951 <input type="text" name="input" ng-model="example.text" 23952 ng-pattern="example.word" required ng-trim="false"> 23953 </label> 23954 <div role="alert"> 23955 <span class="error" ng-show="myForm.input.$error.required"> 23956 Required!</span> 23957 <span class="error" ng-show="myForm.input.$error.pattern"> 23958 Single word only!</span> 23959 </div> 23960 <code>text = {{example.text}}</code><br/> 23961 <code>myForm.input.$valid = {{myForm.input.$valid}}</code><br/> 23962 <code>myForm.input.$error = {{myForm.input.$error}}</code><br/> 23963 <code>myForm.$valid = {{myForm.$valid}}</code><br/> 23964 <code>myForm.$error.required = {{!!myForm.$error.required}}</code><br/> 23965 </form> 23966 </file> 23967 <file name="protractor.js" type="protractor"> 23968 var text = element(by.binding('example.text')); 23969 var valid = element(by.binding('myForm.input.$valid')); 23970 var input = element(by.model('example.text')); 23971 23972 it('should initialize to model', function() { 23973 expect(text.getText()).toContain('guest'); 23974 expect(valid.getText()).toContain('true'); 23975 }); 23976 23977 it('should be invalid if empty', function() { 23978 input.clear(); 23979 input.sendKeys(''); 23980 23981 expect(text.getText()).toEqual('text ='); 23982 expect(valid.getText()).toContain('false'); 23983 }); 23984 23985 it('should be invalid if multi word', function() { 23986 input.clear(); 23987 input.sendKeys('hello world'); 23988 23989 expect(valid.getText()).toContain('false'); 23990 }); 23991 </file> 23992 </example> 23993 */ 23994 'text': textInputType, 23995 23996 /** 23997 * @ngdoc input 23998 * @name input[date] 23999 * 24000 * @description 24001 * Input with date validation and transformation. In browsers that do not yet support 24002 * the HTML5 date input, a text element will be used. In that case, text must be entered in a valid ISO-8601 24003 * date format (yyyy-MM-dd), for example: `2009-01-06`. Since many 24004 * modern browsers do not yet support this input type, it is important to provide cues to users on the 24005 * expected input format via a placeholder or label. 24006 * 24007 * The model must always be a Date object, otherwise Angular will throw an error. 24008 * Invalid `Date` objects (dates whose `getTime()` is `NaN`) will be rendered as an empty string. 24009 * 24010 * The timezone to be used to read/write the `Date` instance in the model can be defined using 24011 * {@link ng.directive:ngModelOptions ngModelOptions}. By default, this is the timezone of the browser. 24012 * 24013 * @param {string} ngModel Assignable angular expression to data-bind to. 24014 * @param {string=} name Property name of the form under which the control is published. 24015 * @param {string=} min Sets the `min` validation error key if the value entered is less than `min`. This must be a 24016 * valid ISO date string (yyyy-MM-dd). You can also use interpolation inside this attribute 24017 * (e.g. `min="{{minDate | date:'yyyy-MM-dd'}}"`). Note that `min` will also add native HTML5 24018 * constraint validation. 24019 * @param {string=} max Sets the `max` validation error key if the value entered is greater than `max`. This must be 24020 * a valid ISO date string (yyyy-MM-dd). You can also use interpolation inside this attribute 24021 * (e.g. `max="{{maxDate | date:'yyyy-MM-dd'}}"`). Note that `max` will also add native HTML5 24022 * constraint validation. 24023 * @param {(date|string)=} ngMin Sets the `min` validation constraint to the Date / ISO date string 24024 * the `ngMin` expression evaluates to. Note that it does not set the `min` attribute. 24025 * @param {(date|string)=} ngMax Sets the `max` validation constraint to the Date / ISO date string 24026 * the `ngMax` expression evaluates to. Note that it does not set the `max` attribute. 24027 * @param {string=} required Sets `required` validation error key if the value is not entered. 24028 * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to 24029 * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of 24030 * `required` when you want to data-bind to the `required` attribute. 24031 * @param {string=} ngChange Angular expression to be executed when input changes due to user 24032 * interaction with the input element. 24033 * 24034 * @example 24035 <example name="date-input-directive" module="dateInputExample"> 24036 <file name="index.html"> 24037 <script> 24038 angular.module('dateInputExample', []) 24039 .controller('DateController', ['$scope', function($scope) { 24040 $scope.example = { 24041 value: new Date(2013, 9, 22) 24042 }; 24043 }]); 24044 </script> 24045 <form name="myForm" ng-controller="DateController as dateCtrl"> 24046 <label for="exampleInput">Pick a date in 2013:</label> 24047 <input type="date" id="exampleInput" name="input" ng-model="example.value" 24048 placeholder="yyyy-MM-dd" min="2013-01-01" max="2013-12-31" required /> 24049 <div role="alert">
24050 <span class="error" ng-show="myForm.input.$error.required"> 24051 Required!</span> 24052 <span class="error" ng-show="myForm.input.$error.date"> 24053 Not a valid date!</span> 24054 </div> 24055 <tt>value = {{example.value | date: "yyyy-MM-dd"}}</tt><br/> 24056 <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/> 24057 <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/> 24058 <tt>myForm.$valid = {{myForm.$valid}}</tt><br/> 24059 <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/> 24060 </form> 24061 </file> 24062 <file name="protractor.js" type="protractor"> 24063 var value = element(by.binding('example.value | date: "yyyy-MM-dd"')); 24064 var valid = element(by.binding('myForm.input.$valid')); 24065 24066 // currently protractor/webdriver does not support 24067 // sending keys to all known HTML5 input controls 24068 // for various browsers (see https://github.com/angular/protractor/issues/562). 24069 function setInput(val) { 24070 // set the value of the element and force validation. 24071 var scr = "var ipt = document.getElementById('exampleInput'); " + 24072 "ipt.value = '" + val + "';" + 24073 "angular.element(ipt).scope().$apply(function(s) { s.myForm[ipt.name].$setViewValue('" + val + "'); });"; 24074 browser.executeScript(scr); 24075 } 24076 24077 it('should initialize to model', function() { 24078 expect(value.getText()).toContain('2013-10-22'); 24079 expect(valid.getText()).toContain('myForm.input.$valid = true'); 24080 }); 24081 24082 it('should be invalid if empty', function() { 24083 setInput(''); 24084 expect(value.getText()).toEqual('value ='); 24085 expect(valid.getText()).toContain('myForm.input.$valid = false'); 24086 }); 24087 24088 it('should be invalid if over max', function() { 24089 setInput('2015-01-01'); 24090 expect(value.getText()).toContain(''); 24091 expect(valid.getText()).toContain('myForm.input.$valid = false'); 24092 }); 24093 </file> 24094 </example> 24095 */ 24096 'date': createDateInputType('date', DATE_REGEXP, 24097 createDateParser(DATE_REGEXP, ['yyyy', 'MM', 'dd']), 24098 'yyyy-MM-dd'), 24099 24100 /** 24101 * @ngdoc input 24102 * @name input[datetime-local] 24103 * 24104 * @description 24105 * Input with datetime validation and transformation. In browsers that do not yet support 24106 * the HTML5 date input, a text element will be used. In that case, the text must be entered in a valid ISO-8601 24107 * local datetime format (yyyy-MM-ddTHH:mm:ss), for example: `2010-12-28T14:57:00`. 24108 * 24109 * The model must always be a Date object, otherwise Angular will throw an error. 24110 * Invalid `Date` objects (dates whose `getTime()` is `NaN`) will be rendered as an empty string. 24111 * 24112 * The timezone to be used to read/write the `Date` instance in the model can be defined using 24113 * {@link ng.directive:ngModelOptions ngModelOptions}. By default, this is the timezone of the browser. 24114 * 24115 * @param {string} ngModel Assignable angular expression to data-bind to. 24116 * @param {string=} name Property name of the form under which the control is published. 24117 * @param {string=} min Sets the `min` validation error key if the value entered is less than `min`. 24118 * This must be a valid ISO datetime format (yyyy-MM-ddTHH:mm:ss). You can also use interpolation 24119 * inside this attribute (e.g. `min="{{minDatetimeLocal | date:'yyyy-MM-ddTHH:mm:ss'}}"`). 24120 * Note that `min` will also add native HTML5 constraint validation. 24121 * @param {string=} max Sets the `max` validation error key if the value entered is greater than `max`. 24122 * This must be a valid ISO datetime format (yyyy-MM-ddTHH:mm:ss). You can also use interpolation 24123 * inside this attribute (e.g. `max="{{maxDatetimeLocal | date:'yyyy-MM-ddTHH:mm:ss'}}"`). 24124 * Note that `max` will also add native HTML5 constraint validation. 24125 * @param {(date|string)=} ngMin Sets the `min` validation error key to the Date / ISO datetime string 24126 * the `ngMin` expression evaluates to. Note that it does not set the `min` attribute. 24127 * @param {(date|string)=} ngMax Sets the `max` validation error key to the Date / ISO datetime string 24128 * the `ngMax` expression evaluates to. Note that it does not set the `max` attribute. 24129 * @param {string=} required Sets `required` validation error key if the value is not entered. 24130 * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to 24131 * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of 24132 * `required` when you want to data-bind to the `required` attribute. 24133 * @param {string=} ngChange Angular expression to be executed when input changes due to user 24134 * interaction with the input element. 24135 * 24136 * @example 24137 <example name="datetimelocal-input-directive" module="dateExample"> 24138 <file name="index.html"> 24139 <script> 24140 angular.module('dateExample', []) 24141 .controller('DateController', ['$scope', function($scope) { 24142 $scope.example = { 24143 value: new Date(2010, 11, 28, 14, 57) 24144 }; 24145 }]); 24146 </script> 24147 <form name="myForm" ng-controller="DateController as dateCtrl"> 24148 <label for="exampleInput">Pick a date between in 2013:</label> 24149 <input type="datetime-local" id="exampleInput" name="input" ng-model="example.value" 24150 placeholder="yyyy-MM-ddTHH:mm:ss" min="2001-01-01T00:00:00" max="2013-12-31T00:00:00" required /> 24151 <div role="alert">
24152 <span class="error" ng-show="myForm.input.$error.required"> 24153 Required!</span> 24154 <span class="error" ng-show="myForm.input.$error.datetimelocal"> 24155 Not a valid date!</span> 24156 </div> 24157 <tt>value = {{example.value | date: "yyyy-MM-ddTHH:mm:ss"}}</tt><br/> 24158 <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/> 24159 <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/> 24160 <tt>myForm.$valid = {{myForm.$valid}}</tt><br/> 24161 <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/> 24162 </form> 24163 </file> 24164 <file name="protractor.js" type="protractor"> 24165 var value = element(by.binding('example.value | date: "yyyy-MM-ddTHH:mm:ss"')); 24166 var valid = element(by.binding('myForm.input.$valid')); 24167 24168 // currently protractor/webdriver does not support 24169 // sending keys to all known HTML5 input controls 24170 // for various browsers (https://github.com/angular/protractor/issues/562). 24171 function setInput(val) { 24172 // set the value of the element and force validation. 24173 var scr = "var ipt = document.getElementById('exampleInput'); " + 24174 "ipt.value = '" + val + "';" + 24175 "angular.element(ipt).scope().$apply(function(s) { s.myForm[ipt.name].$setViewValue('" + val + "'); });"; 24176 browser.executeScript(scr); 24177 } 24178 24179 it('should initialize to model', function() { 24180 expect(value.getText()).toContain('2010-12-28T14:57:00'); 24181 expect(valid.getText()).toContain('myForm.input.$valid = true'); 24182 }); 24183 24184 it('should be invalid if empty', function() { 24185 setInput(''); 24186 expect(value.getText()).toEqual('value ='); 24187 expect(valid.getText()).toContain('myForm.input.$valid = false'); 24188 }); 24189 24190 it('should be invalid if over max', function() { 24191 setInput('2015-01-01T23:59:00'); 24192 expect(value.getText()).toContain(''); 24193 expect(valid.getText()).toContain('myForm.input.$valid = false'); 24194 }); 24195 </file> 24196 </example> 24197 */ 24198 'datetime-local': createDateInputType('datetimelocal', DATETIMELOCAL_REGEXP, 24199 createDateParser(DATETIMELOCAL_REGEXP, ['yyyy', 'MM', 'dd', 'HH', 'mm', 'ss', 'sss']), 24200 'yyyy-MM-ddTHH:mm:ss.sss'), 24201 24202 /** 24203 * @ngdoc input 24204 * @name input[time] 24205 * 24206 * @description 24207 * Input with time validation and transformation. In browsers that do not yet support 24208 * the HTML5 time input, a text element will be used. In that case, the text must be entered in a valid ISO-8601 24209 * local time format (HH:mm:ss), for example: `14:57:00`. Model must be a Date object. This binding will always output a 24210 * Date object to the model of January 1, 1970, or local date `new Date(1970, 0, 1, HH, mm, ss)`. 24211 * 24212 * The model must always be a Date object, otherwise Angular will throw an error. 24213 * Invalid `Date` objects (dates whose `getTime()` is `NaN`) will be rendered as an empty string. 24214 * 24215 * The timezone to be used to read/write the `Date` instance in the model can be defined using 24216 * {@link ng.directive:ngModelOptions ngModelOptions}. By default, this is the timezone of the browser. 24217 * 24218 * @param {string} ngModel Assignable angular expression to data-bind to. 24219 * @param {string=} name Property name of the form under which the control is published. 24220 * @param {string=} min Sets the `min` validation error key if the value entered is less than `min`. 24221 * This must be a valid ISO time format (HH:mm:ss). You can also use interpolation inside this 24222 * attribute (e.g. `min="{{minTime | date:'HH:mm:ss'}}"`). Note that `min` will also add 24223 * native HTML5 constraint validation. 24224 * @param {string=} max Sets the `max` validation error key if the value entered is greater than `max`. 24225 * This must be a valid ISO time format (HH:mm:ss). You can also use interpolation inside this 24226 * attribute (e.g. `max="{{maxTime | date:'HH:mm:ss'}}"`). Note that `max` will also add 24227 * native HTML5 constraint validation. 24228 * @param {(date|string)=} ngMin Sets the `min` validation constraint to the Date / ISO time string the 24229 * `ngMin` expression evaluates to. Note that it does not set the `min` attribute. 24230 * @param {(date|string)=} ngMax Sets the `max` validation constraint to the Date / ISO time string the 24231 * `ngMax` expression evaluates to. Note that it does not set the `max` attribute. 24232 * @param {string=} required Sets `required` validation error key if the value is not entered. 24233 * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to 24234 * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of 24235 * `required` when you want to data-bind to the `required` attribute. 24236 * @param {string=} ngChange Angular expression to be executed when input changes due to user 24237 * interaction with the input element. 24238 * 24239 * @example 24240 <example name="time-input-directive" module="timeExample"> 24241 <file name="index.html"> 24242 <script> 24243 angular.module('timeExample', []) 24244 .controller('DateController', ['$scope', function($scope) { 24245 $scope.example = { 24246 value: new Date(1970, 0, 1, 14, 57, 0) 24247 }; 24248 }]); 24249 </script> 24250 <form name="myForm" ng-controller="DateController as dateCtrl"> 24251 <label for="exampleInput">Pick a time between 8am and 5pm:</label> 24252 <input type="time" id="exampleInput" name="input" ng-model="example.value" 24253 placeholder="HH:mm:ss" min="08:00:00" max="17:00:00" required /> 24254 <div role="alert">
24255 <span class="error" ng-show="myForm.input.$error.required"> 24256 Required!</span> 24257 <span class="error" ng-show="myForm.input.$error.time"> 24258 Not a valid date!</span> 24259 </div> 24260 <tt>value = {{example.value | date: "HH:mm:ss"}}</tt><br/> 24261 <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/> 24262 <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/> 24263 <tt>myForm.$valid = {{myForm.$valid}}</tt><br/> 24264 <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/> 24265 </form> 24266 </file> 24267 <file name="protractor.js" type="protractor"> 24268 var value = element(by.binding('example.value | date: "HH:mm:ss"')); 24269 var valid = element(by.binding('myForm.input.$valid')); 24270 24271 // currently protractor/webdriver does not support 24272 // sending keys to all known HTML5 input controls 24273 // for various browsers (https://github.com/angular/protractor/issues/562). 24274 function setInput(val) { 24275 // set the value of the element and force validation. 24276 var scr = "var ipt = document.getElementById('exampleInput'); " + 24277 "ipt.value = '" + val + "';" + 24278 "angular.element(ipt).scope().$apply(function(s) { s.myForm[ipt.name].$setViewValue('" + val + "'); });"; 24279 browser.executeScript(scr); 24280 } 24281 24282 it('should initialize to model', function() { 24283 expect(value.getText()).toContain('14:57:00'); 24284 expect(valid.getText()).toContain('myForm.input.$valid = true'); 24285 }); 24286 24287 it('should be invalid if empty', function() { 24288 setInput(''); 24289 expect(value.getText()).toEqual('value ='); 24290 expect(valid.getText()).toContain('myForm.input.$valid = false'); 24291 }); 24292 24293 it('should be invalid if over max', function() { 24294 setInput('23:59:00'); 24295 expect(value.getText()).toContain(''); 24296 expect(valid.getText()).toContain('myForm.input.$valid = false'); 24297 }); 24298 </file> 24299 </example> 24300 */ 24301 'time': createDateInputType('time', TIME_REGEXP, 24302 createDateParser(TIME_REGEXP, ['HH', 'mm', 'ss', 'sss']), 24303 'HH:mm:ss.sss'), 24304 24305 /** 24306 * @ngdoc input 24307 * @name input[week] 24308 * 24309 * @description 24310 * Input with week-of-the-year validation and transformation to Date. In browsers that do not yet support 24311 * the HTML5 week input, a text element will be used. In that case, the text must be entered in a valid ISO-8601 24312 * week format (yyyy-W##), for example: `2013-W02`. 24313 * 24314 * The model must always be a Date object, otherwise Angular will throw an error. 24315 * Invalid `Date` objects (dates whose `getTime()` is `NaN`) will be rendered as an empty string. 24316 * 24317 * The timezone to be used to read/write the `Date` instance in the model can be defined using 24318 * {@link ng.directive:ngModelOptions ngModelOptions}. By default, this is the timezone of the browser. 24319 * 24320 * @param {string} ngModel Assignable angular expression to data-bind to. 24321 * @param {string=} name Property name of the form under which the control is published. 24322 * @param {string=} min Sets the `min` validation error key if the value entered is less than `min`. 24323 * This must be a valid ISO week format (yyyy-W##). You can also use interpolation inside this 24324 * attribute (e.g. `min="{{minWeek | date:'yyyy-Www'}}"`). Note that `min` will also add 24325 * native HTML5 constraint validation. 24326 * @param {string=} max Sets the `max` validation error key if the value entered is greater than `max`. 24327 * This must be a valid ISO week format (yyyy-W##). You can also use interpolation inside this 24328 * attribute (e.g. `max="{{maxWeek | date:'yyyy-Www'}}"`). Note that `max` will also add 24329 * native HTML5 constraint validation. 24330 * @param {(date|string)=} ngMin Sets the `min` validation constraint to the Date / ISO week string 24331 * the `ngMin` expression evaluates to. Note that it does not set the `min` attribute. 24332 * @param {(date|string)=} ngMax Sets the `max` validation constraint to the Date / ISO week string 24333 * the `ngMax` expression evaluates to. Note that it does not set the `max` attribute. 24334 * @param {string=} required Sets `required` validation error key if the value is not entered. 24335 * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to 24336 * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of 24337 * `required` when you want to data-bind to the `required` attribute. 24338 * @param {string=} ngChange Angular expression to be executed when input changes due to user 24339 * interaction with the input element. 24340 * 24341 * @example 24342 <example name="week-input-directive" module="weekExample"> 24343 <file name="index.html"> 24344 <script> 24345 angular.module('weekExample', []) 24346 .controller('DateController', ['$scope', function($scope) { 24347 $scope.example = { 24348 value: new Date(2013, 0, 3) 24349 }; 24350 }]); 24351 </script> 24352 <form name="myForm" ng-controller="DateController as dateCtrl"> 24353 <label>Pick a date between in 2013: 24354 <input id="exampleInput" type="week" name="input" ng-model="example.value" 24355 placeholder="YYYY-W##" min="2012-W32" 24356 max="2013-W52" required /> 24357 </label> 24358 <div role="alert">
24359 <span class="error" ng-show="myForm.input.$error.required"> 24360 Required!</span> 24361 <span class="error" ng-show="myForm.input.$error.week"> 24362 Not a valid date!</span> 24363 </div> 24364 <tt>value = {{example.value | date: "yyyy-Www"}}</tt><br/> 24365 <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/> 24366 <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/> 24367 <tt>myForm.$valid = {{myForm.$valid}}</tt><br/> 24368 <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/> 24369 </form> 24370 </file> 24371 <file name="protractor.js" type="protractor"> 24372 var value = element(by.binding('example.value | date: "yyyy-Www"')); 24373 var valid = element(by.binding('myForm.input.$valid')); 24374 24375 // currently protractor/webdriver does not support 24376 // sending keys to all known HTML5 input controls 24377 // for various browsers (https://github.com/angular/protractor/issues/562). 24378 function setInput(val) { 24379 // set the value of the element and force validation. 24380 var scr = "var ipt = document.getElementById('exampleInput'); " + 24381 "ipt.value = '" + val + "';" + 24382 "angular.element(ipt).scope().$apply(function(s) { s.myForm[ipt.name].$setViewValue('" + val + "'); });"; 24383 browser.executeScript(scr); 24384 } 24385 24386 it('should initialize to model', function() { 24387 expect(value.getText()).toContain('2013-W01'); 24388 expect(valid.getText()).toContain('myForm.input.$valid = true'); 24389 }); 24390 24391 it('should be invalid if empty', function() { 24392 setInput(''); 24393 expect(value.getText()).toEqual('value ='); 24394 expect(valid.getText()).toContain('myForm.input.$valid = false'); 24395 }); 24396 24397 it('should be invalid if over max', function() { 24398 setInput('2015-W01'); 24399 expect(value.getText()).toContain(''); 24400 expect(valid.getText()).toContain('myForm.input.$valid = false'); 24401 }); 24402 </file> 24403 </example> 24404 */ 24405 'week': createDateInputType('week', WEEK_REGEXP, weekParser, 'yyyy-Www'), 24406 24407 /** 24408 * @ngdoc input 24409 * @name input[month] 24410 * 24411 * @description 24412 * Input with month validation and transformation. In browsers that do not yet support 24413 * the HTML5 month input, a text element will be used. In that case, the text must be entered in a valid ISO-8601 24414 * month format (yyyy-MM), for example: `2009-01`. 24415 * 24416 * The model must always be a Date object, otherwise Angular will throw an error. 24417 * Invalid `Date` objects (dates whose `getTime()` is `NaN`) will be rendered as an empty string. 24418 * If the model is not set to the first of the month, the next view to model update will set it 24419 * to the first of the month. 24420 * 24421 * The timezone to be used to read/write the `Date` instance in the model can be defined using 24422 * {@link ng.directive:ngModelOptions ngModelOptions}. By default, this is the timezone of the browser. 24423 * 24424 * @param {string} ngModel Assignable angular expression to data-bind to. 24425 * @param {string=} name Property name of the form under which the control is published. 24426 * @param {string=} min Sets the `min` validation error key if the value entered is less than `min`. 24427 * This must be a valid ISO month format (yyyy-MM). You can also use interpolation inside this 24428 * attribute (e.g. `min="{{minMonth | date:'yyyy-MM'}}"`). Note that `min` will also add 24429 * native HTML5 constraint validation. 24430 * @param {string=} max Sets the `max` validation error key if the value entered is greater than `max`. 24431 * This must be a valid ISO month format (yyyy-MM). You can also use interpolation inside this 24432 * attribute (e.g. `max="{{maxMonth | date:'yyyy-MM'}}"`). Note that `max` will also add 24433 * native HTML5 constraint validation. 24434 * @param {(date|string)=} ngMin Sets the `min` validation constraint to the Date / ISO week string 24435 * the `ngMin` expression evaluates to. Note that it does not set the `min` attribute. 24436 * @param {(date|string)=} ngMax Sets the `max` validation constraint to the Date / ISO week string 24437 * the `ngMax` expression evaluates to. Note that it does not set the `max` attribute. 24438 24439 * @param {string=} required Sets `required` validation error key if the value is not entered. 24440 * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to 24441 * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of 24442 * `required` when you want to data-bind to the `required` attribute. 24443 * @param {string=} ngChange Angular expression to be executed when input changes due to user 24444 * interaction with the input element. 24445 * 24446 * @example 24447 <example name="month-input-directive" module="monthExample"> 24448 <file name="index.html"> 24449 <script> 24450 angular.module('monthExample', []) 24451 .controller('DateController', ['$scope', function($scope) { 24452 $scope.example = { 24453 value: new Date(2013, 9, 1) 24454 }; 24455 }]); 24456 </script> 24457 <form name="myForm" ng-controller="DateController as dateCtrl"> 24458 <label for="exampleInput">Pick a month in 2013:</label> 24459 <input id="exampleInput" type="month" name="input" ng-model="example.value" 24460 placeholder="yyyy-MM" min="2013-01" max="2013-12" required /> 24461 <div role="alert">
24462 <span class="error" ng-show="myForm.input.$error.required"> 24463 Required!</span> 24464 <span class="error" ng-show="myForm.input.$error.month"> 24465 Not a valid month!</span> 24466 </div> 24467 <tt>value = {{example.value | date: "yyyy-MM"}}</tt><br/> 24468 <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/> 24469 <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/> 24470 <tt>myForm.$valid = {{myForm.$valid}}</tt><br/> 24471 <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/> 24472 </form> 24473 </file> 24474 <file name="protractor.js" type="protractor"> 24475 var value = element(by.binding('example.value | date: "yyyy-MM"')); 24476 var valid = element(by.binding('myForm.input.$valid')); 24477 24478 // currently protractor/webdriver does not support 24479 // sending keys to all known HTML5 input controls 24480 // for various browsers (https://github.com/angular/protractor/issues/562). 24481 function setInput(val) { 24482 // set the value of the element and force validation. 24483 var scr = "var ipt = document.getElementById('exampleInput'); " + 24484 "ipt.value = '" + val + "';" + 24485 "angular.element(ipt).scope().$apply(function(s) { s.myForm[ipt.name].$setViewValue('" + val + "'); });"; 24486 browser.executeScript(scr); 24487 } 24488 24489 it('should initialize to model', function() { 24490 expect(value.getText()).toContain('2013-10'); 24491 expect(valid.getText()).toContain('myForm.input.$valid = true'); 24492 }); 24493 24494 it('should be invalid if empty', function() { 24495 setInput(''); 24496 expect(value.getText()).toEqual('value ='); 24497 expect(valid.getText()).toContain('myForm.input.$valid = false'); 24498 }); 24499 24500 it('should be invalid if over max', function() { 24501 setInput('2015-01'); 24502 expect(value.getText()).toContain(''); 24503 expect(valid.getText()).toContain('myForm.input.$valid = false'); 24504 }); 24505 </file> 24506 </example> 24507 */ 24508 'month': createDateInputType('month', MONTH_REGEXP, 24509 createDateParser(MONTH_REGEXP, ['yyyy', 'MM']), 24510 'yyyy-MM'), 24511 24512 /** 24513 * @ngdoc input 24514 * @name input[number] 24515 * 24516 * @description 24517 * Text input with number validation and transformation. Sets the `number` validation 24518 * error if not a valid number. 24519 * 24520 * <div class="alert alert-warning"> 24521 * The model must always be of type `number` otherwise Angular will throw an error. 24522 * Be aware that a string containing a number is not enough. See the {@link ngModel:numfmt} 24523 * error docs for more information and an example of how to convert your model if necessary. 24524 * </div> 24525 * 24526 * ## Issues with HTML5 constraint validation 24527 * 24528 * In browsers that follow the 24529 * [HTML5 specification](https://html.spec.whatwg.org/multipage/forms.html#number-state-%28type=number%29), 24530 * `input[number]` does not work as expected with {@link ngModelOptions `ngModelOptions.allowInvalid`}. 24531 * If a non-number is entered in the input, the browser will report the value as an empty string, 24532 * which means the view / model values in `ngModel` and subsequently the scope value 24533 * will also be an empty string. 24534 * 24535 * 24536 * @param {string} ngModel Assignable angular expression to data-bind to. 24537 * @param {string=} name Property name of the form under which the control is published. 24538 * @param {string=} min Sets the `min` validation error key if the value entered is less than `min`. 24539 * Can be interpolated. 24540 * @param {string=} max Sets the `max` validation error key if the value entered is greater than `max`. 24541 * Can be interpolated. 24542 * @param {string=} ngMin Like `min`, sets the `min` validation error key if the value entered is less than `ngMin`, 24543 * but does not trigger HTML5 native validation. Takes an expression. 24544 * @param {string=} ngMax Like `max`, sets the `max` validation error key if the value entered is greater than `ngMax`, 24545 * but does not trigger HTML5 native validation. Takes an expression. 24546 * @param {string=} step Sets the `step` validation error key if the value entered does not fit the `step` constraint. 24547 * Can be interpolated. 24548 * @param {string=} ngStep Like `step`, sets the `step` validation error key if the value entered does not fit the `ngStep` constraint, 24549 * but does not trigger HTML5 native validation. Takes an expression. 24550 * @param {string=} required Sets `required` validation error key if the value is not entered. 24551 * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to 24552 * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of 24553 * `required` when you want to data-bind to the `required` attribute. 24554 * @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than 24555 * minlength. 24556 * @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than 24557 * maxlength. Setting the attribute to a negative or non-numeric value, allows view values of 24558 * any length. 24559 * @param {string=} pattern Similar to `ngPattern` except that the attribute value is the actual string 24560 * that contains the regular expression body that will be converted to a regular expression 24561 * as in the ngPattern directive. 24562 * @param {string=} ngPattern Sets `pattern` validation error key if the ngModel {@link ngModel.NgModelController#$viewValue $viewValue} 24563 * does not match a RegExp found by evaluating the Angular expression given in the attribute value. 24564 * If the expression evaluates to a RegExp object, then this is used directly. 24565 * If the expression evaluates to a string, then it will be converted to a RegExp 24566 * after wrapping it in `^` and `$` characters. For instance, `"abc"` will be converted to 24567 * `new RegExp('^abc$')`.<br /> 24568 * **Note:** Avoid using the `g` flag on the RegExp, as it will cause each successive search to 24569 * start at the index of the last search's match, thus not taking the whole input value into 24570 * account. 24571 * @param {string=} ngChange Angular expression to be executed when input changes due to user 24572 * interaction with the input element. 24573 * 24574 * @example 24575 <example name="number-input-directive" module="numberExample"> 24576 <file name="index.html"> 24577 <script> 24578 angular.module('numberExample', [])
24579 .controller('ExampleController', ['$scope', function($scope) { 24580 $scope.example = { 24581 value: 12 24582 }; 24583 }]); 24584 </script> 24585 <form name="myForm" ng-controller="ExampleController"> 24586 <label>Number: 24587 <input type="number" name="input" ng-model="example.value" 24588 min="0" max="99" required> 24589 </label> 24590 <div role="alert"> 24591 <span class="error" ng-show="myForm.input.$error.required"> 24592 Required!</span> 24593 <span class="error" ng-show="myForm.input.$error.number"> 24594 Not valid number!</span> 24595 </div> 24596 <tt>value = {{example.value}}</tt><br/> 24597 <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/> 24598 <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/> 24599 <tt>myForm.$valid = {{myForm.$valid}}</tt><br/> 24600 <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/> 24601 </form> 24602 </file> 24603 <file name="protractor.js" type="protractor"> 24604 var value = element(by.binding('example.value')); 24605 var valid = element(by.binding('myForm.input.$valid')); 24606 var input = element(by.model('example.value')); 24607 24608 it('should initialize to model', function() { 24609 expect(value.getText()).toContain('12'); 24610 expect(valid.getText()).toContain('true'); 24611 }); 24612 24613 it('should be invalid if empty', function() { 24614 input.clear(); 24615 input.sendKeys(''); 24616 expect(value.getText()).toEqual('value ='); 24617 expect(valid.getText()).toContain('false'); 24618 }); 24619 24620 it('should be invalid if over max', function() { 24621 input.clear(); 24622 input.sendKeys('123'); 24623 expect(value.getText()).toEqual('value ='); 24624 expect(valid.getText()).toContain('false'); 24625 }); 24626 </file> 24627 </example> 24628 */ 24629 'number': numberInputType, 24630 24631 24632 /** 24633 * @ngdoc input 24634 * @name input[url] 24635 * 24636 * @description 24637 * Text input with URL validation. Sets the `url` validation error key if the content is not a 24638 * valid URL. 24639 * 24640 * <div class="alert alert-warning"> 24641 * **Note:** `input[url]` uses a regex to validate urls that is derived from the regex 24642 * used in Chromium. If you need stricter validation, you can use `ng-pattern` or modify 24643 * the built-in validators (see the {@link guide/forms Forms guide}) 24644 * </div> 24645 * 24646 * @param {string} ngModel Assignable angular expression to data-bind to. 24647 * @param {string=} name Property name of the form under which the control is published. 24648 * @param {string=} required Sets `required` validation error key if the value is not entered. 24649 * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to 24650 * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of 24651 * `required` when you want to data-bind to the `required` attribute. 24652 * @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than 24653 * minlength. 24654 * @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than 24655 * maxlength. Setting the attribute to a negative or non-numeric value, allows view values of 24656 * any length. 24657 * @param {string=} pattern Similar to `ngPattern` except that the attribute value is the actual string 24658 * that contains the regular expression body that will be converted to a regular expression 24659 * as in the ngPattern directive. 24660 * @param {string=} ngPattern Sets `pattern` validation error key if the ngModel {@link ngModel.NgModelController#$viewValue $viewValue} 24661 * does not match a RegExp found by evaluating the Angular expression given in the attribute value. 24662 * If the expression evaluates to a RegExp object, then this is used directly. 24663 * If the expression evaluates to a string, then it will be converted to a RegExp 24664 * after wrapping it in `^` and `$` characters. For instance, `"abc"` will be converted to 24665 * `new RegExp('^abc$')`.<br /> 24666 * **Note:** Avoid using the `g` flag on the RegExp, as it will cause each successive search to 24667 * start at the index of the last search's match, thus not taking the whole input value into 24668 * account. 24669 * @param {string=} ngChange Angular expression to be executed when input changes due to user 24670 * interaction with the input element. 24671 * 24672 * @example 24673 <example name="url-input-directive" module="urlExample"> 24674 <file name="index.html"> 24675 <script> 24676 angular.module('urlExample', [])
24677 .controller('ExampleController', ['$scope', function($scope) { 24678 $scope.url = { 24679 text: 'http://google.com' 24680 }; 24681 }]); 24682 </script> 24683 <form name="myForm" ng-controller="ExampleController"> 24684 <label>URL: 24685 <input type="url" name="input" ng-model="url.text" required> 24686 <label> 24687 <div role="alert"> 24688 <span class="error" ng-show="myForm.input.$error.required"> 24689 Required!</span> 24690 <span class="error" ng-show="myForm.input.$error.url"> 24691 Not valid url!</span> 24692 </div> 24693 <tt>text = {{url.text}}</tt><br/> 24694 <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/> 24695 <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/> 24696 <tt>myForm.$valid = {{myForm.$valid}}</tt><br/> 24697 <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/> 24698 <tt>myForm.$error.url = {{!!myForm.$error.url}}</tt><br/> 24699 </form> 24700 </file> 24701 <file name="protractor.js" type="protractor"> 24702 var text = element(by.binding('url.text')); 24703 var valid = element(by.binding('myForm.input.$valid')); 24704 var input = element(by.model('url.text')); 24705 24706 it('should initialize to model', function() { 24707 expect(text.getText()).toContain('http://google.com'); 24708 expect(valid.getText()).toContain('true'); 24709 }); 24710 24711 it('should be invalid if empty', function() { 24712 input.clear(); 24713 input.sendKeys(''); 24714 24715 expect(text.getText()).toEqual('text ='); 24716 expect(valid.getText()).toContain('false'); 24717 }); 24718 24719 it('should be invalid if not url', function() { 24720 input.clear(); 24721 input.sendKeys('box'); 24722 24723 expect(valid.getText()).toContain('false'); 24724 }); 24725 </file> 24726 </example> 24727 */ 24728 'url': urlInputType, 24729 24730 24731 /** 24732 * @ngdoc input 24733 * @name input[email] 24734 * 24735 * @description 24736 * Text input with email validation. Sets the `email` validation error key if not a valid email 24737 * address. 24738 * 24739 * <div class="alert alert-warning"> 24740 * **Note:** `input[email]` uses a regex to validate email addresses that is derived from the regex 24741 * used in Chromium. If you need stricter validation (e.g. requiring a top-level domain), you can 24742 * use `ng-pattern` or modify the built-in validators (see the {@link guide/forms Forms guide}) 24743 * </div> 24744 * 24745 * @param {string} ngModel Assignable angular expression to data-bind to. 24746 * @param {string=} name Property name of the form under which the control is published. 24747 * @param {string=} required Sets `required` validation error key if the value is not entered. 24748 * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to 24749 * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of 24750 * `required` when you want to data-bind to the `required` attribute. 24751 * @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than 24752 * minlength. 24753 * @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than 24754 * maxlength. Setting the attribute to a negative or non-numeric value, allows view values of 24755 * any length. 24756 * @param {string=} pattern Similar to `ngPattern` except that the attribute value is the actual string 24757 * that contains the regular expression body that will be converted to a regular expression 24758 * as in the ngPattern directive. 24759 * @param {string=} ngPattern Sets `pattern` validation error key if the ngModel {@link ngModel.NgModelController#$viewValue $viewValue} 24760 * does not match a RegExp found by evaluating the Angular expression given in the attribute value. 24761 * If the expression evaluates to a RegExp object, then this is used directly. 24762 * If the expression evaluates to a string, then it will be converted to a RegExp 24763 * after wrapping it in `^` and `$` characters. For instance, `"abc"` will be converted to 24764 * `new RegExp('^abc$')`.<br /> 24765 * **Note:** Avoid using the `g` flag on the RegExp, as it will cause each successive search to 24766 * start at the index of the last search's match, thus not taking the whole input value into 24767 * account. 24768 * @param {string=} ngChange Angular expression to be executed when input changes due to user 24769 * interaction with the input element. 24770 * 24771 * @example 24772 <example name="email-input-directive" module="emailExample"> 24773 <file name="index.html"> 24774 <script> 24775 angular.module('emailExample', [])
24776 .controller('ExampleController', ['$scope', function($scope) { 24777 $scope.email = { 24778 text: '[email protected]' 24779 }; 24780 }]); 24781 </script> 24782 <form name="myForm" ng-controller="ExampleController"> 24783 <label>Email: 24784 <input type="email" name="input" ng-model="email.text" required> 24785 </label> 24786 <div role="alert"> 24787 <span class="error" ng-show="myForm.input.$error.required"> 24788 Required!</span> 24789 <span class="error" ng-show="myForm.input.$error.email"> 24790 Not valid email!</span> 24791 </div> 24792 <tt>text = {{email.text}}</tt><br/> 24793 <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/> 24794 <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/> 24795 <tt>myForm.$valid = {{myForm.$valid}}</tt><br/> 24796 <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/> 24797 <tt>myForm.$error.email = {{!!myForm.$error.email}}</tt><br/> 24798 </form> 24799 </file> 24800 <file name="protractor.js" type="protractor"> 24801 var text = element(by.binding('email.text')); 24802 var valid = element(by.binding('myForm.input.$valid')); 24803 var input = element(by.model('email.text')); 24804 24805 it('should initialize to model', function() { 24806 expect(text.getText()).toContain('[email protected]'); 24807 expect(valid.getText()).toContain('true'); 24808 }); 24809 24810 it('should be invalid if empty', function() { 24811 input.clear(); 24812 input.sendKeys(''); 24813 expect(text.getText()).toEqual('text ='); 24814 expect(valid.getText()).toContain('false'); 24815 }); 24816 24817 it('should be invalid if not email', function() { 24818 input.clear(); 24819 input.sendKeys('xxx'); 24820 24821 expect(valid.getText()).toContain('false'); 24822 }); 24823 </file> 24824 </example> 24825 */ 24826 'email': emailInputType, 24827 24828 24829 /** 24830 * @ngdoc input 24831 * @name input[radio] 24832 * 24833 * @description 24834 * HTML radio button. 24835 * 24836 * @param {string} ngModel Assignable angular expression to data-bind to. 24837 * @param {string} value The value to which the `ngModel` expression should be set when selected. 24838 * Note that `value` only supports `string` values, i.e. the scope model needs to be a string, 24839 * too. Use `ngValue` if you need complex models (`number`, `object`, ...). 24840 * @param {string=} name Property name of the form under which the control is published. 24841 * @param {string=} ngChange Angular expression to be executed when input changes due to user 24842 * interaction with the input element. 24843 * @param {string} ngValue Angular expression to which `ngModel` will be be set when the radio 24844 * is selected. Should be used instead of the `value` attribute if you need 24845 * a non-string `ngModel` (`boolean`, `array`, ...). 24846 * 24847 * @example 24848 <example name="radio-input-directive" module="radioExample"> 24849 <file name="index.html"> 24850 <script> 24851 angular.module('radioExample', []) 24852 .controller('ExampleController', ['$scope', function($scope) { 24853 $scope.color = { 24854 name: 'blue' 24855 }; 24856 $scope.specialValue = { 24857 "id": "12345", 24858 "value": "green" 24859 }; 24860 }]); 24861 </script>
24862 <form name="myForm" ng-controller="ExampleController"> 24863 <label> 24864 <input type="radio" ng-model="color.name" value="red"> 24865 Red 24866 </label><br/> 24867 <label> 24868 <input type="radio" ng-model="color.name" ng-value="specialValue"> 24869 Green 24870 </label><br/> 24871 <label> 24872 <input type="radio" ng-model="color.name" value="blue"> 24873 Blue 24874 </label><br/> 24875 <tt>color = {{color.name | json}}</tt><br/> 24876 </form> 24877 Note that `ng-value="specialValue"` sets radio item's value to be the value of `$scope.specialValue`. 24878 </file> 24879 <file name="protractor.js" type="protractor"> 24880 it('should change state', function() { 24881 var inputs = element.all(by.model('color.name')); 24882 var color = element(by.binding('color.name')); 24883 24884 expect(color.getText()).toContain('blue'); 24885 24886 inputs.get(0).click(); 24887 expect(color.getText()).toContain('red'); 24888 24889 inputs.get(1).click(); 24890 expect(color.getText()).toContain('green'); 24891 }); 24892 </file> 24893 </example> 24894 */ 24895 'radio': radioInputType, 24896 24897 /** 24898 * @ngdoc input 24899 * @name input[range] 24900 * 24901 * @description 24902 * Native range input with validation and transformation. 24903 * 24904 * The model for the range input must always be a `Number`. 24905 * 24906 * IE9 and other browsers that do not support the `range` type fall back 24907 * to a text input without any default values for `min`, `max` and `step`. Model binding, 24908 * validation and number parsing are nevertheless supported. 24909 * 24910 * Browsers that support range (latest Chrome, Safari, Firefox, Edge) treat `input[range]` 24911 * in a way that never allows the input to hold an invalid value. That means: 24912 * - any non-numerical value is set to `(max + min) / 2`. 24913 * - any numerical value that is less than the current min val, or greater than the current max val 24914 * is set to the min / max val respectively. 24915 * - additionally, the current `step` is respected, so the nearest value that satisfies a step 24916 * is used. 24917 * 24918 * See the [HTML Spec on input[type=range]](https://www.w3.org/TR/html5/forms.html#range-state-(type=range)) 24919 * for more info. 24920 * 24921 * This has the following consequences for Angular: 24922 * 24923 * Since the element value should always reflect the current model value, a range input 24924 * will set the bound ngModel expression to the value that the browser has set for the 24925 * input element. For example, in the following input `<input type="range" ng-model="model.value">`, 24926 * if the application sets `model.value = null`, the browser will set the input to `'50'`. 24927 * Angular will then set the model to `50`, to prevent input and model value being out of sync. 24928 * 24929 * That means the model for range will immediately be set to `50` after `ngModel` has been 24930 * initialized. It also means a range input can never have the required error. 24931 * 24932 * This does not only affect changes to the model value, but also to the values of the `min`, 24933 * `max`, and `step` attributes. When these change in a way that will cause the browser to modify 24934 * the input value, Angular will also update the model value. 24935 * 24936 * Automatic value adjustment also means that a range input element can never have the `required`, 24937 * `min`, or `max` errors. 24938 * 24939 * However, `step` is currently only fully implemented by Firefox. Other browsers have problems 24940 * when the step value changes dynamically - they do not adjust the element value correctly, but 24941 * instead may set the `stepMismatch` error. If that's the case, the Angular will set the `step` 24942 * error on the input, and set the model to `undefined`. 24943 * 24944 * Note that `input[range]` is not compatible with`ngMax`, `ngMin`, and `ngStep`, because they do 24945 * not set the `min` and `max` attributes, which means that the browser won't automatically adjust 24946 * the input value based on their values, and will always assume min = 0, max = 100, and step = 1. 24947 * 24948 * @param {string} ngModel Assignable angular expression to data-bind to. 24949 * @param {string=} name Property name of the form under which the control is published. 24950 * @param {string=} min Sets the `min` validation to ensure that the value entered is greater 24951 * than `min`. Can be interpolated. 24952 * @param {string=} max Sets the `max` validation to ensure that the value entered is less than `max`. 24953 * Can be interpolated. 24954 * @param {string=} step Sets the `step` validation to ensure that the value entered matches the `step` 24955 * Can be interpolated. 24956 * @param {string=} ngChange Angular expression to be executed when the ngModel value changes due 24957 *
vendor: 2,634 bytes, lines 24957-25023
24957 to user interaction with the input element. 24958 * @param {expression=} ngChecked If the expression is truthy, then the `checked` attribute will be set on the 24959 * element. **Note** : `ngChecked` should not be used alongside `ngModel`. 24960 * Checkout {@link ng.directive:ngChecked ngChecked} for usage. 24961 * 24962 * @example 24963 <example name="range-input-directive" module="rangeExample"> 24964 <file name="index.html"> 24965 <script> 24966 angular.module('rangeExample', []) 24967 .controller('ExampleController', ['$scope', function($scope) { 24968 $scope.value = 75; 24969 $scope.min = 10; 24970 $scope.max = 90; 24971 }]); 24972 </script> 24973 <form name="myForm" ng-controller="ExampleController"> 24974 24975 Model as range: <input type="range" name="range" ng-model="value" min="{{min}}" max="{{max}}"> 24976 <hr> 24977 Model as number: <input type="number" ng-model="value"><br> 24978 Min: <input type="number" ng-model="min"><br> 24979 Max: <input type="number" ng-model="max"><br> 24980 value = <code>{{value}}</code><br/> 24981 myForm.range.$valid = <code>{{myForm.range.$valid}}</code><br/> 24982 myForm.range.$error = <code>{{myForm.range.$error}}</code> 24983 </form> 24984 </file> 24985 </example> 24986 24987 * ## Range Input with ngMin & ngMax attributes 24988 24989 * @example 24990 <example name="range-input-directive-ng" module="rangeExample"> 24991 <file name="index.html"> 24992 <script> 24993 angular.module('rangeExample', []) 24994 .controller('ExampleController', ['$scope', function($scope) { 24995 $scope.value = 75; 24996 $scope.min = 10; 24997 $scope.max = 90; 24998 }]); 24999 </script> 25000 <form name="myForm" ng-controller="ExampleController"> 25001 Model as range: <input type="range" name="range" ng-model="value" ng-min="min" ng-max="max"> 25002 <hr> 25003 Model as number: <input type="number" ng-model="value"><br> 25004 Min: <input type="number" ng-model="min"><br> 25005 Max: <input type="number" ng-model="max"><br> 25006 value = <code>{{value}}</code><br/> 25007 myForm.range.$valid = <code>{{myForm.range.$valid}}</code><br/> 25008 myForm.range.$error = <code>{{myForm.range.$error}}</code> 25009 </form> 25010 </file> 25011 </example> 25012 25013 */ 25014 'range': rangeInputType, 25015 25016 /** 25017 * @ngdoc input 25018 * @name input[checkbox] 25019 * 25020 * @description 25021 * HTML checkbox. 25022 * 25023 * @param {string} ngModel Assignable
25023angular expression to data-bind to. 25024 * @param {string=} name Property name of the form under which the control is published. 25025 * @param {expression=} ngTrueValue The value to which the expression should be set when selected. 25026 * @param {expression=} ngFalseValue The value to which the expression should be set when not selected. 25027 * @param {string=} ngChange Angular expression to be executed when input changes due to user 25028 * interaction with the input element. 25029 * 25030 * @example 25031 <example name="checkbox-input-directive" module="checkboxExample"> 25032 <file name="index.html"> 25033 <script> 25034 angular.module('checkboxExample', []) 25035 .controller('ExampleController', ['$scope', function($scope) {
25036 $scope.checkboxModel = { 25037 value1 : true, 25038 value2 : 'YES' 25039 }; 25040 }]); 25041 </script> 25042 <form name="myForm" ng-controller="ExampleController"> 25043 <label>Value1: 25044 <input type="checkbox" ng-model="checkboxModel.value1"> 25045 </label><br/> 25046 <label>Value2: 25047 <input type="checkbox" ng-model="checkboxModel.value2" 25048 ng-true-value="'YES'" ng-false-value="'NO'"> 25049 </label><br/> 25050 <tt>value1 = {{checkboxModel.value1}}</tt><br/> 25051 <tt>value2 = {{checkboxModel.value2}}</tt><br/> 25052 </form> 25053 </file> 25054 <file name="protractor.js" type="protractor"> 25055 it('should change state', function() { 25056 var value1 = element(by.binding('checkboxModel.value1')); 25057 var value2 = element(by.binding('checkboxModel.value2')); 25058 25059 expect(value1.getText()).toContain('true'); 25060 expect(value2.getText()).toContain('YES'); 25061 25062 element(by.model('checkboxModel.value1')).click(); 25063 element(by.model('checkboxModel.value2')).click(); 25064 25065 expect(value1.getText()).toContain('false'); 25066 expect(value2.getText()).toContain('NO'); 25067 }); 25068 </file> 25069 </example> 25070 */ 25071 'checkbox': checkboxInputType, 25072 25073 'hidden': noop, 25074 'button': noop, 25075 'submit': noop, 25076 'reset': noop, 25077 'file': noop 25078}; 25079 25080function stringBasedInputType(ctrl) { 25081 ctrl.$formatters.push(function(value) { 25082 return ctrl.$isEmpty(value) ? value : value.toString(); 25083 }); 25084} 25085 25086function textInputType(scope, element, attr, ctrl, $sniffer, $browser) { 25087 baseInputType(scope, element, attr, ctrl, $sniffer, $browser); 25088 stringBasedInputType(ctrl); 25089} 25090 25091function baseInputType(scope, element, attr, ctrl, $sniffer, $browser) { 25092 var type = lowercase(element[0].type); 25093 25094 // In composition mode, users are still inputting intermediate text buffer, 25095 // hold the listener until composition is done. 25096 // More about composition events: https://developer.mozilla.org/en-US/docs/Web/API/CompositionEvent 25097 if (!$sniffer.android) { 25098 var composing = false; 25099 25100 element.on('compositionstart', function() { 25101 composing = true; 25102 }); 25103 25104 element.on('compositionend', function() { 25105 composing = false; 25106 listener(); 25107 }); 25108 } 25109 25110 var timeout; 25111 25112 var listener = function(ev) { 25113 if (timeout) { 25114 $browser.defer.cancel(timeout); 25115 timeout = null; 25116 } 25117 if (composing) return; 25118 var value = element.val(), 25119 event = ev && ev.type; 25120 25121 // By default we will trim the value 25122 // If the attribute ng-trim exists we will avoid trimming 25123 // If input type is 'password', the value is never trimmed 25124 if (type !== 'password' && (!attr.ngTrim || attr.ngTrim !== 'false')) { 25125 value = trim(value); 25126 } 25127 25128 // If a control is suffering from bad input (due to native validators), browsers discard its 25129 // value, so it may be necessary to revalidate (by calling $setViewValue again) even if the 25130 // control's value is the same empty value twice in a row. 25131 if (ctrl.$viewValue !== value || (value === '' && ctrl.$$hasNativeValidators)) { 25132 ctrl.$setViewValue(value, event); 25133 } 25134 }; 25135 25136 // if the browser does support "input" event, we are fine - except on IE9 which doesn't fire the 25137 // input event on backspace, delete or cut 25138 if ($sniffer.hasEvent('input')) { 25139 element.on('input', listener); 25140 } else { 25141 var deferListener = function(ev, input, origValue) { 25142 if (!timeout) { 25143 timeout = $browser.defer(function() { 25144 timeout = null; 25145 if (!input || input.value !== origValue) { 25146 listener(ev); 25147 } 25148 }); 25149 } 25150 }; 25151 25152 element.on('keydown', /** @this */ function(event) { 25153 var key = event.keyCode; 25154 25155 // ignore 25156 // command modifiers arrows 25157 if (key === 91 || (15 < key && key < 19) || (37 <= key && key <= 40)) return; 25158 25159 deferListener(event, this, this.value); 25160 }); 25161 25162 // if user modifies input value using context menu in IE, we need "paste" and "cut" events to catch it 25163 if ($sniffer.hasEvent('paste')) { 25164 element.on('paste cut', deferListener); 25165 } 25166 } 25167 25168 // if user paste into input using mouse on older browser 25169 // or form autocomplete on newer browser, we need "change" event to catch it 25170 element.on('change', listener); 25171 25172 // Some native input types (date-family) have the ability to change validity without 25173 // firing any input/change events. 25174 // For these event types, when native validators are present and the browser supports the type, 25175 // check for validity changes on various DOM events. 25176 if (PARTIAL_VALIDATION_TYPES[type] && ctrl.$$hasNativeValidators && type === attr.type) { 25177 element.on(PARTIAL_VALIDATION_EVENTS, /** @this */ function(ev) { 25178 if (!timeout) {
vendor: 17,297 bytes, lines 25179-25715
25179 var validity = this[VALIDITY_STATE_PROPERTY]; 25180 var origBadInput = validity.badInput; 25181 var origTypeMismatch = validity.typeMismatch; 25182 timeout = $browser.defer(function() { 25183 timeout = null; 25184 if (validity.badInput !== origBadInput || validity.typeMismatch !== origTypeMismatch) { 25185 listener(ev); 25186 } 25187 }); 25188 } 25189 }); 25190 } 25191 25192 ctrl.$render = function() { 25193 // Workaround for Firefox validation #12102. 25194 var value = ctrl.$isEmpty(ctrl.$viewValue) ? '' : ctrl.$viewValue; 25195 if (element.val() !== value) { 25196 element.val(value); 25197 } 25198 }; 25199} 25200 25201function weekParser(isoWeek, existingDate) { 25202 if (isDate(isoWeek)) { 25203 return isoWeek; 25204 } 25205 25206 if (isString(isoWeek)) { 25207 WEEK_REGEXP.lastIndex = 0; 25208 var parts = WEEK_REGEXP.exec(isoWeek); 25209 if (parts) { 25210 var year = +parts[1], 25211 week = +parts[2], 25212 hours = 0, 25213 minutes = 0, 25214 seconds = 0, 25215 milliseconds = 0, 25216 firstThurs = getFirstThursdayOfYear(year), 25217 addDays = (week - 1) * 7; 25218 25219 if (existingDate) { 25220 hours = existingDate.getHours(); 25221 minutes = existingDate.getMinutes(); 25222 seconds = existingDate.getSeconds(); 25223 milliseconds = existingDate.getMilliseconds(); 25224 } 25225 25226 return new Date(year, 0, firstThurs.getDate() + addDays, hours, minutes, seconds, milliseconds); 25227 } 25228 } 25229 25230 return NaN; 25231} 25232 25233function createDateParser(regexp, mapping) { 25234 return function(iso, date) { 25235 var parts, map; 25236 25237 if (isDate(iso)) { 25238 return iso; 25239 } 25240 25241 if (isString(iso)) { 25242 // When a date is JSON'ified to wraps itself inside of an extra 25243 // set of double quotes. This makes the date parsing code unable 25244 // to match the date string and parse it as a date. 25245 if (iso.charAt(0) === '"' && iso.charAt(iso.length - 1) === '"') { 25246 iso = iso.substring(1, iso.length - 1); 25247 } 25248 if (ISO_DATE_REGEXP.test(iso)) { 25249 return new Date(iso); 25250 } 25251 regexp.lastIndex = 0; 25252 parts = regexp.exec(iso); 25253 25254 if (parts) { 25255 parts.shift(); 25256 if (date) { 25257 map = { 25258 yyyy: date.getFullYear(), 25259 MM: date.getMonth() + 1, 25260 dd: date.getDate(), 25261 HH: date.getHours(), 25262 mm: date.getMinutes(), 25263 ss: date.getSeconds(), 25264 sss: date.getMilliseconds() / 1000 25265 }; 25266 } else { 25267 map = { yyyy: 1970, MM: 1, dd: 1, HH: 0, mm: 0, ss: 0, sss: 0 }; 25268 } 25269 25270 forEach(parts, function(part, index) { 25271 if (index < mapping.length) { 25272 map[mapping[index]] = +part; 25273 } 25274 }); 25275 return new Date(map.yyyy, map.MM - 1, map.dd, map.HH, map.mm, map.ss || 0, map.sss * 1000 || 0); 25276 } 25277 } 25278 25279 return NaN; 25280 }; 25281} 25282 25283function createDateInputType(type, regexp, parseDate, format) { 25284 return function dynamicDateInputType(scope, element, attr, ctrl, $sniffer, $browser, $filter) { 25285 badInputChecker(scope, element, attr, ctrl); 25286 baseInputType(scope, element, attr, ctrl, $sniffer, $browser); 25287 var timezone = ctrl && ctrl.$options.getOption('timezone'); 25288 var previousDate; 25289 25290 ctrl.$$parserName = type; 25291 ctrl.$parsers.push(function(value) { 25292 if (ctrl.$isEmpty(value)) return null; 25293 if (regexp.test(value)) { 25294 // Note: We cannot read ctrl.$modelValue, as there might be a different 25295 // parser/formatter in the processing chain so that the model 25296 // contains some different data format! 25297 var parsedDate = parseDate(value, previousDate); 25298 if (timezone) { 25299 parsedDate = convertTimezoneToLocal(parsedDate, timezone); 25300 } 25301 return parsedDate; 25302 } 25303 return undefined; 25304 }); 25305 25306 ctrl.$formatters.push(function(value) { 25307 if (value && !isDate(value)) { 25308 throw ngModelMinErr('datefmt', 'Expected `{0}` to be a date', value); 25309 } 25310 if (isValidDate(value)) { 25311 previousDate = value; 25312 if (previousDate && timezone) { 25313 previousDate = convertTimezoneToLocal(previousDate, timezone, true); 25314 } 25315 return $filter('date')(value, format, timezone); 25316 } else { 25317 previousDate = null; 25318 return ''; 25319 } 25320 }); 25321 25322 if (isDefined(attr.min) || attr.ngMin) { 25323 var minVal; 25324 ctrl.$validators.min = function(value) { 25325 return !isValidDate(value) || isUndefined(minVal) || parseDate(value) >= minVal; 25326 }; 25327 attr.$observe('min', function(val) { 25328 minVal = parseObservedDateValue(val); 25329 ctrl.$validate(); 25330 }); 25331 } 25332 25333 if (isDefined(attr.max) || attr.ngMax) { 25334 var maxVal; 25335 ctrl.$validators.max = function(value) { 25336 return !isValidDate(value) || isUndefined(maxVal) || parseDate(value) <= maxVal; 25337 }; 25338 attr.$observe('max', function(val) { 25339 maxVal = parseObservedDateValue(val); 25340 ctrl.$validate(); 25341 }); 25342 } 25343 25344 function isValidDate(value) { 25345 // Invalid Date: getTime() returns NaN 25346 return value && !(value.getTime && value.getTime() !== value.getTime()); 25347 } 25348 25349 function parseObservedDateValue(val) { 25350 return isDefined(val) && !isDate(val) ? parseDate(val) || undefined : val; 25351 } 25352 }; 25353} 25354 25355function badInputChecker(scope, element, attr, ctrl) { 25356 var node = element[0]; 25357 var nativeValidation = ctrl.$$hasNativeValidators = isObject(node.validity); 25358 if (nativeValidation) { 25359 ctrl.$parsers.push(function(value) { 25360 var validity = element.prop(VALIDITY_STATE_PROPERTY) || {}; 25361 return validity.badInput || validity.typeMismatch ? undefined : value; 25362 }); 25363 } 25364} 25365 25366function numberFormatterParser(ctrl) { 25367 ctrl.$$parserName = 'number'; 25368 ctrl.$parsers.push(function(value) { 25369 if (ctrl.$isEmpty(value)) return null; 25370 if (NUMBER_REGEXP.test(value)) return parseFloat(value); 25371 return undefined; 25372 }); 25373 25374 ctrl.$formatters.push(function(value) { 25375 if (!ctrl.$isEmpty(value)) { 25376 if (!isNumber(value)) { 25377 throw ngModelMinErr('numfmt', 'Expected `{0}` to be a number', value); 25378 } 25379 value = value.toString(); 25380 } 25381 return value; 25382 }); 25383} 25384 25385function parseNumberAttrVal(val) { 25386 if (isDefined(val) && !isNumber(val)) { 25387 val = parseFloat(val); 25388 } 25389 return !isNumberNaN(val) ? val : undefined; 25390} 25391 25392function isNumberInteger(num) { 25393 // See http://stackoverflow.com/questions/14636536/how-to-check-if-a-variable-is-an-integer-in-javascript#14794066 25394 // (minus the assumption that `num` is a number) 25395 25396 // eslint-disable-next-line no-bitwise 25397 return (num | 0) === num; 25398} 25399 25400function countDecimals(num) { 25401 var numString = num.toString(); 25402 var decimalSymbolIndex = numString.indexOf('.'); 25403 25404 if (decimalSymbolIndex === -1) { 25405 if (-1 < num && num < 1) { 25406 // It may be in the exponential notation format (`1e-X`) 25407 var match = /e-(\d+)$/.exec(numString); 25408 25409 if (match) { 25410 return Number(match[1]); 25411 } 25412 } 25413 25414 return 0; 25415 } 25416 25417 return numString.length - decimalSymbolIndex - 1; 25418} 25419 25420function isValidForStep(viewValue, stepBase, step) { 25421 // At this point `stepBase` and `step` are expected to be non-NaN values 25422 // and `viewValue` is expected to be a valid stringified number. 25423 var value = Number(viewValue); 25424 25425 var isNonIntegerValue = !isNumberInteger(value); 25426 var isNonIntegerStepBase = !isNumberInteger(stepBase); 25427 var isNonIntegerStep = !isNumberInteger(step); 25428 25429 // Due to limitations in Floating Point Arithmetic (e.g. `0.3 - 0.2 !== 0.1` or 25430 // `0.5 % 0.1 !== 0`), we need to convert all numbers to integers. 25431 if (isNonIntegerValue || isNonIntegerStepBase || isNonIntegerStep) { 25432 var valueDecimals = isNonIntegerValue ? countDecimals(value) : 0; 25433 var stepBaseDecimals = isNonIntegerStepBase ? countDecimals(stepBase) : 0; 25434 var stepDecimals = isNonIntegerStep ? countDecimals(step) : 0; 25435 25436 var decimalCount = Math.max(valueDecimals, stepBaseDecimals, stepDecimals); 25437 var multiplier = Math.pow(10, decimalCount); 25438 25439 value = value * multiplier; 25440 stepBase = stepBase * multiplier; 25441 step = step * multiplier; 25442 25443 if (isNonIntegerValue) value = Math.round(value); 25444 if (isNonIntegerStepBase) stepBase = Math.round(stepBase); 25445 if (isNonIntegerStep) step = Math.round(step); 25446 } 25447 25448 return (value - stepBase) % step === 0; 25449} 25450 25451function numberInputType(scope, element, attr, ctrl, $sniffer, $browser) { 25452 badInputChecker(scope, element, attr, ctrl); 25453 numberFormatterParser(ctrl); 25454 baseInputType(scope, element, attr, ctrl, $sniffer, $browser); 25455 25456 var minVal; 25457 var maxVal; 25458 25459 if (isDefined(attr.min) || attr.ngMin) { 25460 ctrl.$validators.min = function(value) { 25461 return ctrl.$isEmpty(value) || isUndefined(minVal) || value >= minVal; 25462 }; 25463 25464 attr.$observe('min', function(val) { 25465 minVal = parseNumberAttrVal(val); 25466 // TODO(matsko): implement validateLater to reduce number of validations 25467 ctrl.$validate(); 25468 }); 25469 } 25470 25471 if (isDefined(attr.max) || attr.ngMax) { 25472 ctrl.$validators.max = function(value) { 25473 return ctrl.$isEmpty(value) || isUndefined(maxVal) || value <= maxVal; 25474 }; 25475 25476 attr.$observe('max', function(val) { 25477 maxVal = parseNumberAttrVal(val); 25478 // TODO(matsko): implement validateLater to reduce number of validations 25479 ctrl.$validate(); 25480 }); 25481 } 25482 25483 if (isDefined(attr.step) || attr.ngStep) { 25484 var stepVal; 25485 ctrl.$validators.step = function(modelValue, viewValue) { 25486 return ctrl.$isEmpty(viewValue) || isUndefined(stepVal) || 25487 isValidForStep(viewValue, minVal || 0, stepVal); 25488 }; 25489 25490 attr.$observe('step', function(val) { 25491 stepVal = parseNumberAttrVal(val); 25492 // TODO(matsko): implement validateLater to reduce number of validations 25493 ctrl.$validate(); 25494 }); 25495 } 25496} 25497 25498function rangeInputType(scope, element, attr, ctrl, $sniffer, $browser) { 25499 badInputChecker(scope, element, attr, ctrl); 25500 numberFormatterParser(ctrl); 25501 baseInputType(scope, element, attr, ctrl, $sniffer, $browser); 25502 25503 var supportsRange = ctrl.$$hasNativeValidators && element[0].type === 'range', 25504 minVal = supportsRange ? 0 : undefined, 25505 maxVal = supportsRange ? 100 : undefined, 25506 stepVal = supportsRange ? 1 : undefined, 25507 validity = element[0].validity, 25508 hasMinAttr = isDefined(attr.min), 25509 hasMaxAttr = isDefined(attr.max), 25510 hasStepAttr = isDefined(attr.step); 25511 25512 var originalRender = ctrl.$render; 25513 25514 ctrl.$render = supportsRange && isDefined(validity.rangeUnderflow) && isDefined(validity.rangeOverflow) ? 25515 //Browsers that implement range will set these values automatically, but reading the adjusted values after 25516 //$render would cause the min / max validators to be applied with the wrong value 25517 function rangeRender() { 25518 originalRender(); 25519 ctrl.$setViewValue(element.val()); 25520 } : 25521 originalRender; 25522 25523 if (hasMinAttr) { 25524 ctrl.$validators.min = supportsRange ? 25525 // Since all browsers set the input to a valid value, we don't need to check validity 25526 function noopMinValidator() { return true; } : 25527 // non-support browsers validate the min val 25528 function minValidator(modelValue, viewValue) { 25529 return ctrl.$isEmpty(viewValue) || isUndefined(minVal) || viewValue >= minVal; 25530 }; 25531 25532 setInitialValueAndObserver('min', minChange); 25533 } 25534 25535 if (hasMaxAttr) { 25536 ctrl.$validators.max = supportsRange ? 25537 // Since all browsers set the input to a valid value, we don't need to check validity 25538 function noopMaxValidator() { return true; } : 25539 // non-support browsers validate the max val 25540 function maxValidator(modelValue, viewValue) { 25541 return ctrl.$isEmpty(viewValue) || isUndefined(maxVal) || viewValue <= maxVal; 25542 }; 25543 25544 setInitialValueAndObserver('max', maxChange); 25545 } 25546 25547 if (hasStepAttr) { 25548 ctrl.$validators.step = supportsRange ? 25549 function nativeStepValidator() { 25550 // Currently, only FF implements the spec on step change correctly (i.e. adjusting the 25551 // input element value to a valid value). It's possible that other browsers set the stepMismatch 25552 // validity error instead, so we can at least report an error in that case. 25553 return !validity.stepMismatch; 25554 } : 25555 // ngStep doesn't set the setp attr, so the browser doesn't adjust the input value as setting step would 25556 function stepValidator(modelValue, viewValue) { 25557 return ctrl.$isEmpty(viewValue) || isUndefined(stepVal) || 25558 isValidForStep(viewValue, minVal || 0, stepVal); 25559 }; 25560 25561 setInitialValueAndObserver('step', stepChange); 25562 } 25563 25564 function setInitialValueAndObserver(htmlAttrName, changeFn) { 25565 // interpolated attributes set the attribute value only after a digest, but we need the 25566 // attribute value when the input is first rendered, so that the browser can adjust the 25567 // input value based on the min/max value 25568 element.attr(htmlAttrName, attr[htmlAttrName]); 25569 attr.$observe(htmlAttrName, changeFn); 25570 } 25571 25572 function minChange(val) { 25573 minVal = parseNumberAttrVal(val); 25574 // ignore changes before model is initialized 25575 if (isNumberNaN(ctrl.$modelValue)) { 25576 return; 25577 } 25578 25579 if (supportsRange) { 25580 var elVal = element.val(); 25581 // IE11 doesn't set the el val correctly if the minVal is greater than the element value 25582 if (minVal > elVal) { 25583 elVal = minVal; 25584 element.val(elVal); 25585 } 25586 ctrl.$setViewValue(elVal); 25587 } else { 25588 // TODO(matsko): implement validateLater to reduce number of validations 25589 ctrl.$validate(); 25590 } 25591 } 25592 25593 function maxChange(val) { 25594 maxVal = parseNumberAttrVal(val); 25595 // ignore changes before model is initialized 25596 if (isNumberNaN(ctrl.$modelValue)) { 25597 return; 25598 } 25599 25600 if (supportsRange) { 25601 var elVal = element.val(); 25602 // IE11 doesn't set the el val correctly if the maxVal is less than the element value 25603 if (maxVal < elVal) { 25604 element.val(maxVal); 25605 // IE11 and Chrome don't set the value to the minVal when max < min 25606 elVal = maxVal < minVal ? minVal : maxVal; 25607 } 25608 ctrl.$setViewValue(elVal); 25609 } else { 25610 // TODO(matsko): implement validateLater to reduce number of validations 25611 ctrl.$validate(); 25612 } 25613 } 25614 25615 function stepChange(val) { 25616 stepVal = parseNumberAttrVal(val); 25617 // ignore changes before model is initialized 25618 if (isNumberNaN(ctrl.$modelValue)) { 25619 return; 25620 } 25621 25622 // Some browsers don't adjust the input value correctly, but set the stepMismatch error 25623 if (supportsRange && ctrl.$viewValue !== element.val()) { 25624 ctrl.$setViewValue(element.val()); 25625 } else { 25626 // TODO(matsko): implement validateLater to reduce number of validations 25627 ctrl.$validate(); 25628 } 25629 } 25630} 25631 25632function urlInputType(scope, element, attr, ctrl, $sniffer, $browser) { 25633 // Note: no badInputChecker here by purpose as `url` is only a validation 25634 // in browsers, i.e. we can always read out input.value even if it is not valid! 25635 baseInputType(scope, element, attr, ctrl, $sniffer, $browser); 25636 stringBasedInputType(ctrl); 25637 25638 ctrl.$$parserName = 'url'; 25639 ctrl.$validators.url = function(modelValue, viewValue) { 25640 var value = modelValue || viewValue; 25641 return ctrl.$isEmpty(value) || URL_REGEXP.test(value); 25642 }; 25643} 25644 25645function emailInputType(scope, element, attr, ctrl, $sniffer, $browser) { 25646 // Note: no badInputChecker here by purpose as `url` is only a validation 25647 // in browsers, i.e. we can always read out input.value even if it is not valid! 25648 baseInputType(scope, element, attr, ctrl, $sniffer, $browser); 25649 stringBasedInputType(ctrl); 25650 25651 ctrl.$$parserName = 'email'; 25652 ctrl.$validators.email = function(modelValue, viewValue) { 25653 var value = modelValue || viewValue; 25654 return ctrl.$isEmpty(value) || EMAIL_REGEXP.test(value); 25655 }; 25656} 25657 25658function radioInputType(scope, element, attr, ctrl) { 25659 var doTrim = !attr.ngTrim || trim(attr.ngTrim) !== 'false'; 25660 // make the name unique, if not defined 25661 if (isUndefined(attr.name)) { 25662 element.attr('name', nextUid()); 25663 } 25664 25665 var listener = function(ev) { 25666 var value; 25667 if (element[0].checked) { 25668 value = attr.value; 25669 if (doTrim) { 25670 value = trim(value); 25671 } 25672 ctrl.$setViewValue(value, ev && ev.type); 25673 } 25674 }; 25675 25676 element.on('click', listener); 25677 25678 ctrl.$render = function() { 25679 var value = attr.value; 25680 if (doTrim) { 25681 value = trim(value); 25682 } 25683 element[0].checked = (value === ctrl.$viewValue); 25684 }; 25685 25686 attr.$observe('value', ctrl.$render); 25687} 25688 25689function parseConstantExpr($parse, context, name, expression, fallback) { 25690 var parseFn; 25691 if (isDefined(expression)) { 25692 parseFn = $parse(expression); 25693 if (!parseFn.constant) { 25694 throw ngModelMinErr('constexpr', 'Expected constant expression for `{0}`, but saw ' + 25695 '`{1}`.', name, expression); 25696 } 25697 return parseFn(context); 25698 } 25699 return fallback; 25700} 25701 25702function checkboxInputType(scope, element, attr, ctrl, $sniffer, $browser, $filter, $parse) { 25703 var trueValue = parseConstantExpr($parse, scope, 'ngTrueValue', attr.ngTrueValue, true); 25704 var falseValue = parseConstantExpr($parse, scope, 'ngFalseValue', attr.ngFalseValue, false); 25705 25706 var listener = function(ev) { 25707 ctrl.$setViewValue(element[0].checked, ev && ev.type); 25708 }; 25709 25710 element.on('click', listener); 25711 25712 ctrl.$render = function() { 25713 element[0].checked = ctrl.$viewValue; 25714 }; 25715
25716 // Override the standard `$isEmpty` because the $viewValue of an empty checkbox is always set to `false` 25717 // This is because of the parser below, which compares the `$modelValue` with `trueValue` to convert 25718 // it to a boolean. 25719 ctrl.$isEmpty = function(value) { 25720 return value === false; 25721 }; 25722 25723 ctrl.$formatters.push(function(value) { 25724 return equals(value, trueValue); 25725 }); 25726 25727 ctrl.$parsers.push(function(value) { 25728 return value ? trueValue : falseValue; 25729 }); 25730} 25731 25732 25733/** 25734 * @ngdoc directive 25735 * @name textarea 25736 * @restrict E 25737 * 25738 * @description 25739 * HTML textarea element control with angular data-binding. The data-binding and validation 25740 * properties of this element are exactly the same as those of the 25741 * {@link ng.directive:input input element}. 25742 * 25743 * @param {string} ngModel Assignable angular expression to data-bind to. 25744 * @param {string=} name Property name of the form under which the control is published. 25745 * @param {string=} required Sets `required` validation error key if the value is not entered. 25746 * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to 25747 * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of 25748 * `required` when you want to data-bind to the `required` attribute. 25749 * @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than 25750 * minlength. 25751 * @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than 25752 * maxlength. Setting the attribute to a negative or non-numeric value, allows view values of any 25753 * length. 25754 * @param {string=} ngPattern Sets `pattern` validation error key if the ngModel {@link ngModel.NgModelController#$viewValue $viewValue} 25755 * does not match a RegExp found by evaluating the Angular expression given in the attribute value. 25756 * If the expression evaluates to a RegExp object, then this is used directly. 25757 * If the expression evaluates to a string, then it will be converted to a RegExp 25758 * after wrapping it in `^` and `$` characters. For instance, `"abc"` will be converted to 25759 * `new RegExp('^abc$')`.<br /> 25760 * **Note:** Avoid using the `g` flag on the RegExp, as it will cause each successive search to 25761 * start at the index of the last search's match, thus not taking the whole input value into 25762 * account. 25763 * @param {string=} ngChange Angular expression to be executed when input changes due to user 25764 * interaction with the input element. 25765 * @param {boolean=} [ngTrim=true] If set to false Angular will not automatically trim the input. 25766 * 25767 * @knownIssue 25768 * 25769 * When specifying the `placeholder` attribute of `<textarea>`, Internet Explorer will temporarily 25770 * insert the placeholder value as the textarea's content. If the placeholder value contains 25771 * interpolation (`{{ ... }}`), an error will be logged in the console when Angular tries to update 25772 * the value of the by-then-removed text node. This doesn't affect the functionality of the 25773 * textarea, but can be undesirable. 25774 * 25775 * You can work around this Internet Explorer issue by using `ng-attr-placeholder` instead of 25776 * `placeholder` on textareas, whenever you need interpolation in the placeholder value. You can 25777 * find more details on `ngAttr` in the 25778 * [Interpolation](guide/interpolation#-ngattr-for-binding-to-arbitrary-attributes) section of the 25779 * Developer Guide. 25780 */ 25781 25782 25783/** 25784 * @ngdoc directive 25785 * @name input 25786 * @restrict E 25787 * 25788 * @description 25789 * HTML input element control. When used together with {@link ngModel `ngModel`}, it provides data-binding, 25790 * input state control, and validation. 25791 * Input control follows HTML5 input types and polyfills the HTML5 validation behavior for older browsers. 25792 * 25793 * <div class="alert alert-warning"> 25794 * **Note:** Not every feature offered is available for all input types. 25795 * Specifically, data binding and event handling via `ng-model` is unsupported for `input[file]`. 25796 * </div> 25797 * 25798 * @param {string} ngModel Assignable angular expression to data-bind to. 25799 * @param {string=} name Property name of the form under which the control is published. 25800 * @param {string=} required Sets `required` validation error key if the value is not entered. 25801 * @param {boolean=} ngRequired Sets `required` attribute if set to true 25802 * @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than 25803 * minlength. 25804 * @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than 25805 * maxlength. Setting the attribute to a negative or non-numeric value, allows view values of any 25806 * length. 25807 * @param {string=} ngPattern Sets `pattern` validation error key if the ngModel {@link ngModel.NgModelController#$viewValue $viewValue} 25808 * value does not match a RegExp found by evaluating the Angular expression given in the attribute value. 25809 * If the expression evaluates to a RegExp object, then this is used directly. 25810 * If the expression evaluates to a string, then it will be converted to a RegExp 25811 * after wrapping it in `^` and `$` characters. For instance, `"abc"` will be converted to 25812 * `new RegExp('^abc$')`.<br /> 25813 * **Note:** Avoid using the `g` flag on the RegExp, as it will cause each successive search to 25814 * start at the index of the last search's match, thus not taking the whole input value into 25815 * account. 25816 * @param {string=} ngChange Angular expression to be executed when input changes due to user 25817 * interaction with the input element. 25818 * @param {boolean=} [ngTrim=true] If set to false Angular
vendor: 4,842 bytes, lines 25818-25936
25818 will not automatically trim the input. 25819 * This parameter is ignored for input[type=password] controls, which will never trim the 25820 * input. 25821 * 25822 * @example 25823 <example name="input-directive" module="inputExample"> 25824 <file name="index.html"> 25825 <script> 25826 angular.module('inputExample', []) 25827 .controller('ExampleController', ['$scope', function($scope) { 25828 $scope.user = {name: 'guest', last: 'visitor'}; 25829 }]); 25830 </script> 25831 <div ng-controller="ExampleController"> 25832 <form name="myForm"> 25833 <label> 25834 User name: 25835 <input type="text" name="userName" ng-model="user.name" required> 25836 </label> 25837 <div role="alert"> 25838 <span class="error" ng-show="myForm.userName.$error.required"> 25839 Required!</span> 25840 </div> 25841 <label> 25842 Last name: 25843 <input type="text" name="lastName" ng-model="user.last" 25844 ng-minlength="3" ng-maxlength="10"> 25845 </label> 25846 <div role="alert"> 25847 <span class="error" ng-show="myForm.lastName.$error.minlength"> 25848 Too short!</span> 25849 <span class="error" ng-show="myForm.lastName.$error.maxlength"> 25850 Too long!</span> 25851 </div> 25852 </form> 25853 <hr> 25854 <tt>user = {{user}}</tt><br/> 25855 <tt>myForm.userName.$valid = {{myForm.userName.$valid}}</tt><br/> 25856 <tt>myForm.userName.$error = {{myForm.userName.$error}}</tt><br/> 25857 <tt>myForm.lastName.$valid = {{myForm.lastName.$valid}}</tt><br/> 25858 <tt>myForm.lastName.$error = {{myForm.lastName.$error}}</tt><br/> 25859 <tt>myForm.$valid = {{myForm.$valid}}</tt><br/> 25860 <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/> 25861 <tt>myForm.$error.minlength = {{!!myForm.$error.minlength}}</tt><br/> 25862 <tt>myForm.$error.maxlength = {{!!myForm.$error.maxlength}}</tt><br/> 25863 </div> 25864 </file> 25865 <file name="protractor.js" type="protractor"> 25866 var user = element(by.exactBinding('user')); 25867 var userNameValid = element(by.binding('myForm.userName.$valid')); 25868 var lastNameValid = element(by.binding('myForm.lastName.$valid')); 25869 var lastNameError = element(by.binding('myForm.lastName.$error')); 25870 var formValid = element(by.binding('myForm.$valid')); 25871 var userNameInput = element(by.model('user.name')); 25872 var userLastInput = element(by.model('user.last')); 25873 25874 it('should initialize to model', function() { 25875 expect(user.getText()).toContain('{"name":"guest","last":"visitor"}'); 25876 expect(userNameValid.getText()).toContain('true'); 25877 expect(formValid.getText()).toContain('true'); 25878 }); 25879 25880 it('should be invalid if empty when required', function() { 25881 userNameInput.clear(); 25882 userNameInput.sendKeys(''); 25883 25884 expect(user.getText()).toContain('{"last":"visitor"}'); 25885 expect(userNameValid.getText()).toContain('false'); 25886 expect(formValid.getText()).toContain('false'); 25887 }); 25888 25889 it('should be valid if empty when min length is set', function() { 25890 userLastInput.clear(); 25891 userLastInput.sendKeys(''); 25892 25893 expect(user.getText()).toContain('{"name":"guest","last":""}'); 25894 expect(lastNameValid.getText()).toContain('true'); 25895 expect(formValid.getText()).toContain('true'); 25896 }); 25897 25898 it('should be invalid if less than required min length', function() { 25899 userLastInput.clear(); 25900 userLastInput.sendKeys('xx'); 25901 25902 expect(user.getText()).toContain('{"name":"guest"}'); 25903 expect(lastNameValid.getText()).toContain('false'); 25904 expect(lastNameError.getText()).toContain('minlength'); 25905 expect(formValid.getText()).toContain('false'); 25906 }); 25907 25908 it('should be invalid if longer than max length', function() { 25909 userLastInput.clear(); 25910 userLastInput.sendKeys('some ridiculously long name'); 25911 25912 expect(user.getText()).toContain('{"name":"guest"}'); 25913 expect(lastNameValid.getText()).toContain('false'); 25914 expect(lastNameError.getText()).toContain('maxlength'); 25915 expect(formValid.getText()).toContain('false'); 25916 }); 25917 </file> 25918 </example> 25919 */ 25920var inputDirective = ['$browser', '$sniffer', '$filter', '$parse', 25921 function($browser, $sniffer, $filter, $parse) { 25922 return { 25923 restrict: 'E', 25924 require: ['?ngModel'], 25925 link: { 25926 pre: function(scope, element, attr, ctrls) { 25927 if (ctrls[0]) { 25928 (inputType[lowercase(attr.type)] || inputType.text)(scope, element, attr, ctrls[0], $sniffer, 25929 $browser, $filter, $parse); 25930 } 25931 } 25932 } 25933 }; 25934}]; 25935 25936
25937 25938var CONSTANT_VALUE_REGEXP = /^(true|false|\d+)$/; 25939/** 25940 * @ngdoc directive 25941 * @name ngValue 25942 * 25943 * @description 25944 * Binds the given expression to the value of the element. 25945 * 25946 * It is mainly used on {@link input[radio] `input[radio]`} and option elements, 25947 * so that when the element is selected, the {@link ngModel `ngModel`} of that element (or its 25948 * {@link select `select`} parent element) is set to the bound value. It is especially useful 25949 * for dynamically generated lists using {@link ngRepeat `ngRepeat`}, as shown below. 25950 * 25951 * It can also be used to achieve one-way binding of a given expression to an input element 25952 * such as an `input[text]` or a `textarea`, when that element does not use ngModel. 25953 * 25954 * @element input 25955 * @param {string=} ngValue angular expression, whose value will be bound to the `value` attribute 25956 * and `value` property of the element. 25957 * 25958 * @example 25959 <example name="ngValue-directive" module="valueExample"> 25960 <file name="index.html"> 25961 <script> 25962 angular.module('valueExample', []) 25963 .controller('ExampleController', ['$scope', function($scope) { 25964 $scope.names = ['pizza', 'unicorns', 'robots']; 25965 $scope.my = { favorite: 'unicorns' }; 25966 }]); 25967 </script>
25968 <form ng-controller="ExampleController"> 25969 <h2>Which is your favorite?</h2> 25970 <label ng-repeat="name in names" for="{{name}}"> 25971 {{name}} 25972 <input type="radio" 25973 ng-model="my.favorite" 25974 ng-value="name" 25975 id="{{name}}" 25976 name="favorite"> 25977 </label> 25978 <div>You chose {{my.favorite}}</div> 25979 </form> 25980 </file> 25981 <file name="protractor.js" type="protractor"> 25982 var favorite = element(by.binding('my.favorite')); 25983 25984 it('should initialize to model', function() { 25985 expect(favorite.getText()).toContain('unicorns'); 25986 }); 25987 it('should bind the values to the inputs', function() { 25988 element.all(by.model('my.favorite')).get(0).click(); 25989 expect(favorite.getText()).toContain('pizza'); 25990 }); 25991 </file> 25992 </example> 25993 */ 25994var ngValueDirective = function() { 25995 /** 25996 * inputs use the value attribute as their default value if the value property is not set. 25997 * Once the value property has been set (by adding input), it will not react to changes to 25998 * the value attribute anymore. Setting both attribute and property fixes this behavior, and 25999 * makes it possible to use ngValue as a sort of one-way bind. 26000 */ 26001 function updateElementValue(element, attr, value) { 26002 // Support: IE9 only 26003 // In IE9 values are converted to string (e.g. `input.value = null` results in `input.value === 'null'`). 26004 var propValue = isDefined(value) ? value : (msie === 9) ? '' : null; 26005 element.prop('value', propValue); 26006 attr.$set('value', value); 26007 } 26008 26009 return { 26010 restrict: 'A', 26011 priority: 100, 26012 compile: function(tpl, tplAttr) { 26013 if (CONSTANT_VALUE_REGEXP.test(tplAttr.ngValue)) { 26014 return function ngValueConstantLink(scope, elm, attr) { 26015 var value = scope.$eval(attr.ngValue); 26016 updateElementValue(elm, attr, value); 26017 }; 26018 } else { 26019 return function ngValueLink(scope, elm, attr) { 26020 scope.$watch(attr.ngValue, function valueWatchAction(value) { 26021 updateElementValue(elm, attr, value); 26022 }); 26023 }; 26024 } 26025 } 26026 }; 26027}; 26028 26029/** 26030 * @ngdoc directive 26031 * @name ngBind 26032 * @restrict AC 26033 * 26034 * @description 26035 * The `ngBind` attribute tells Angular to replace the text content of the specified HTML element 26036 * with the value of a given expression, and to update the text content when the value of that 26037 * expression changes. 26038 * 26039 * Typically, you don't use `ngBind` directly, but instead you use the double curly markup like 26040 * `{{ expression }}` which is similar but less verbose. 26041 * 26042 * It is preferable to use `ngBind` instead of `{{ expression }}` if a template is momentarily 26043 * displayed by the browser in its raw state before Angular
vendor: 4,777 bytes, lines 26043-26173
26043 compiles it. Since `ngBind` is an 26044 * element attribute, it makes the bindings invisible to the user while the page is loading. 26045 * 26046 * An alternative solution to this problem would be using the 26047 * {@link ng.directive:ngCloak ngCloak} directive. 26048 * 26049 * 26050 * @element ANY 26051 * @param {expression} ngBind {@link guide/expression Expression} to evaluate. 26052 * 26053 * @example 26054 * Enter a name in the Live Preview text box; the greeting below the text box changes instantly. 26055 <example module="bindExample" name="ng-bind"> 26056 <file name="index.html"> 26057 <script> 26058 angular.module('bindExample', []) 26059 .controller('ExampleController', ['$scope', function($scope) { 26060 $scope.name = 'Whirled'; 26061 }]); 26062 </script> 26063 <div ng-controller="ExampleController"> 26064 <label>Enter name: <input type="text" ng-model="name"></label><br> 26065 Hello <span ng-bind="name"></span>! 26066 </div> 26067 </file> 26068 <file name="protractor.js" type="protractor"> 26069 it('should check ng-bind', function() { 26070 var nameInput = element(by.model('name')); 26071 26072 expect(element(by.binding('name')).getText()).toBe('Whirled'); 26073 nameInput.clear(); 26074 nameInput.sendKeys('world'); 26075 expect(element(by.binding('name')).getText()).toBe('world'); 26076 }); 26077 </file> 26078 </example> 26079 */ 26080var ngBindDirective = ['$compile', function($compile) { 26081 return { 26082 restrict: 'AC', 26083 compile: function ngBindCompile(templateElement) { 26084 $compile.$$addBindingClass(templateElement); 26085 return function ngBindLink(scope, element, attr) { 26086 $compile.$$addBindingInfo(element, attr.ngBind); 26087 element = element[0]; 26088 scope.$watch(attr.ngBind, function ngBindWatchAction(value) { 26089 element.textContent = stringify(value); 26090 }); 26091 }; 26092 } 26093 }; 26094}]; 26095 26096 26097/** 26098 * @ngdoc directive 26099 * @name ngBindTemplate 26100 * 26101 * @description 26102 * The `ngBindTemplate` directive specifies that the element 26103 * text content should be replaced with the interpolation of the template 26104 * in the `ngBindTemplate` attribute. 26105 * Unlike `ngBind`, the `ngBindTemplate` can contain multiple `{{` `}}` 26106 * expressions. This directive is needed since some HTML elements 26107 * (such as TITLE and OPTION) cannot contain SPAN elements. 26108 * 26109 * @element ANY 26110 * @param {string} ngBindTemplate template of form 26111 * <tt>{{</tt> <tt>expression</tt> <tt>}}</tt> to eval. 26112 * 26113 * @example 26114 * Try it here: enter text in text box and watch the greeting change. 26115 <example module="bindExample" name="ng-bind-template"> 26116 <file name="index.html"> 26117 <script> 26118 angular.module('bindExample', []) 26119 .controller('ExampleController', ['$scope', function($scope) { 26120 $scope.salutation = 'Hello'; 26121 $scope.name = 'World'; 26122 }]); 26123 </script> 26124 <div ng-controller="ExampleController"> 26125 <label>Salutation: <input type="text" ng-model="salutation"></label><br> 26126 <label>Name: <input type="text" ng-model="name"></label><br> 26127 <pre ng-bind-template="{{salutation}} {{name}}!"></pre> 26128 </div> 26129 </file> 26130 <file name="protractor.js" type="protractor"> 26131 it('should check ng-bind', function() { 26132 var salutationElem = element(by.binding('salutation')); 26133 var salutationInput = element(by.model('salutation')); 26134 var nameInput = element(by.model('name')); 26135 26136 expect(salutationElem.getText()).toBe('Hello World!'); 26137 26138 salutationInput.clear(); 26139 salutationInput.sendKeys('Greetings'); 26140 nameInput.clear(); 26141 nameInput.sendKeys('user'); 26142 26143 expect(salutationElem.getText()).toBe('Greetings user!'); 26144 }); 26145 </file> 26146 </example> 26147 */ 26148var ngBindTemplateDirective = ['$interpolate', '$compile', function($interpolate, $compile) { 26149 return { 26150 compile: function ngBindTemplateCompile(templateElement) { 26151 $compile.$$addBindingClass(templateElement); 26152 return function ngBindTemplateLink(scope, element, attr) { 26153 var interpolateFn = $interpolate(element.attr(attr.$attr.ngBindTemplate)); 26154 $compile.$$addBindingInfo(element, interpolateFn.expressions); 26155 element = element[0]; 26156 attr.$observe('ngBindTemplate', function(value) { 26157 element.textContent = isUndefined(value) ? '' : value; 26158 }); 26159 }; 26160 } 26161 }; 26162}]; 26163 26164 26165/** 26166 * @ngdoc directive 26167 * @name ngBindHtml 26168 * 26169 * @description 26170 * Evaluates the expression and inserts the resulting HTML into the element in a secure way. By default, 26171 * the resulting HTML content will be sanitized using the {@link ngSanitize.$sanitize $sanitize} service. 26172 * To utilize this functionality, ensure that `$sanitize` is available, for example, by including {@link 26173 * ngSanitize} in your module's dependencies (not in core Angular
26173). In order to use {@link ngSanitize} 26174 * in your module's dependencies, you need to include "angular-sanitize.js" in your application. 26175 * 26176 * You may also bypass sanitization for values you know are safe. To do so, bind to 26177 * an explicitly trusted value via {@link ng.$sce#trustAsHtml $sce.trustAsHtml}. See the example 26178 * under {@link ng.$sce#show-me-an-example-using-sce- Strict Contextual Escaping (SCE)}. 26179 * 26180 * Note: If a `$sanitize` service is unavailable and the bound value isn't explicitly trusted, you 26181 * will have an exception (instead of an exploit.) 26182 * 26183 * @element ANY 26184 * @param {expression} ngBindHtml {@link guide/expression Expression} to evaluate. 26185 * 26186 * @example 26187 26188 <example module="bindHtmlExample" deps="angular-sanitize.js" name="ng-bind-html"> 26189 <file name="index.html"> 26190 <div ng-controller="ExampleController"> 26191 <p ng-bind-html="myHTML"></p> 26192 </div> 26193 </file> 26194 26195 <file name="script.js"> 26196 angular.module('bindHtmlExample', ['ngSanitize']) 26197 .controller('ExampleController', ['$scope', function($scope) { 26198 $scope.myHTML = 26199 'I am an <code>HTML</code>string with ' + 26200 '<a href="#">links!</a> and other <em>stuff</em>'; 26201 }]); 26202 </file> 26203 26204 <file name="protractor.js" type="protractor"> 26205 it('should check ng-bind-html', function() { 26206 expect(element(by.binding('myHTML')).getText()).toBe( 26207 'I am an HTMLstring with links! and other stuff'); 26208 }); 26209 </file> 26210 </example> 26211 */ 26212var ngBindHtmlDirective = ['$sce', '$parse', '$compile', function($sce, $parse, $compile) { 26213 return { 26214 restrict: 'A',
26215 compile: function ngBindHtmlCompile(tElement, tAttrs) { 26216 var ngBindHtmlGetter = $parse(tAttrs.ngBindHtml); 26217 var ngBindHtmlWatch = $parse(tAttrs.ngBindHtml, function sceValueOf(val) { 26218 // Unwrap the value to compare the actual inner safe value, not the wrapper object. 26219 return $sce.valueOf(val); 26220 }); 26221 $compile.$$addBindingClass(tElement); 26222 26223 return function ngBindHtmlLink(scope, element, attr) { 26224 $compile.$$addBindingInfo(element, attr.ngBindHtml); 26225 26226 scope.$watch(ngBindHtmlWatch, function ngBindHtmlWatchAction() { 26227 // The watched value is the unwrapped value. To avoid re-escaping, use the direct getter. 26228 var value = ngBindHtmlGetter(scope); 26229 element.html($sce.getTrustedHtml(value) || ''); 26230 }); 26231 }; 26232 } 26233 }; 26234}]; 26235 26236/** 26237 * @ngdoc directive 26238 * @name ngChange 26239 * 26240 * @description 26241 * Evaluate the given expression when the user changes the input. 26242 * The expression is evaluated immediately, unlike the JavaScript onchange event 26243 * which only triggers at the end of a change (usually, when the user leaves the 26244 * form element or presses the return key). 26245 * 26246 * The `ngChange` expression is only evaluated when a change in the input value causes 26247 * a new value to be committed to the model. 26248 * 26249 * It will not be evaluated: 26250 * * if the value returned from the `$parsers` transformation pipeline has not changed 26251 * * if the input has continued to be invalid since the model will stay `null` 26252 * * if the model is changed programmatically and not by a change to the input value 26253 * 26254 * 26255 * Note, this directive requires `ngModel` to be present. 26256 * 26257 * @element input 26258 * @param {expression} ngChange {@link guide/expression Expression} to evaluate upon change 26259 * in input value. 26260 * 26261 * @example 26262 * <example name="ngChange-directive" module="changeExample"> 26263 * <file name="index.html"> 26264 * <script> 26265 * angular.module('changeExample', []) 26266 * .controller('ExampleController', ['$scope', function($scope) { 26267 * $scope.counter = 0; 26268 * $scope.change = function() { 26269 * $scope.counter++; 26270 * }; 26271 * }]); 26272 * </script>
26273 * <div ng-controller="ExampleController"> 26274 * <input type="checkbox" ng-model="confirmed" ng-change="change()" id="ng-change-example1" /> 26275 * <input type="checkbox" ng-model="confirmed" id="ng-change-example2" /> 26276 * <label for="ng-change-example2">Confirmed</label><br /> 26277 * <tt>debug = {{confirmed}}</tt><br/> 26278 * <tt>counter = {{counter}}</tt><br/> 26279 * </div> 26280 * </file> 26281 * <file name="protractor.js" type="protractor"> 26282 * var counter = element(by.binding('counter')); 26283 * var debug = element(by.binding('confirmed')); 26284 * 26285 * it('should evaluate the expression if changing from view', function() { 26286 * expect(counter.getText()).toContain('0'); 26287 * 26288 * element(by.id('ng-change-example1')).click(); 26289 * 26290 * expect(counter.getText()).toContain('1'); 26291 * expect(debug.getText()).toContain('true'); 26292 * }); 26293 * 26294 * it('should not evaluate the expression if changing from model', function() { 26295 * element(by.id('ng-change-example2')).click(); 26296 26297 * expect(counter.getText()).toContain('0'); 26298 * expect(debug.getText()).toContain('true'); 26299 * }); 26300 * </file> 26301 * </example> 26302 */ 26303var ngChangeDirective = valueFn({ 26304 restrict: 'A', 26305 require: 'ngModel', 26306 link: function(scope, element, attr, ctrl) { 26307 ctrl.$viewChangeListeners.push(function() { 26308 scope.$eval(attr.ngChange); 26309 }); 26310 } 26311}); 26312 26313/* exported 26314 ngClassDirective, 26315 ngClassEvenDirective, 26316 ngClassOddDirective 26317*/ 26318 26319function classDirective(name, selector) { 26320 name = 'ngClass' + name; 26321 var indexWatchExpression; 26322 26323 return ['$parse', function($parse) { 26324 return { 26325 restrict: 'AC', 26326 link: function(scope, element, attr) { 26327 var expression = attr[name].trim(); 26328 var isOneTime = (expression.charAt(0) === ':') && (expression.charAt(1) === ':'); 26329 26330 var watchInterceptor = isOneTime ? toFlatValue : toClassString; 26331 var watchExpression = $parse(expression, watchInterceptor); 26332 var watchAction = isOneTime ? ngClassOneTimeWatchAction : ngClassWatchAction; 26333 26334 var classCounts = element.data('$classCounts'); 26335 var oldModulo = true; 26336 var oldClassString; 26337 26338 if (!classCounts) { 26339 // Use createMap() to prevent class assumptions involving property 26340 // names in Object.prototype 26341 classCounts = createMap(); 26342 element.data('$classCounts', classCounts); 26343 } 26344 26345 if (name !== 'ngClass') { 26346 if (!indexWatchExpression) { 26347 indexWatchExpression = $parse('$index', function moduloTwo($index) { 26348 // eslint-disable-next-line no-bitwise 26349 return $index & 1; 26350 }); 26351 } 26352 26353 scope.$watch(indexWatchExpression, ngClassIndexWatchAction); 26354 } 26355 26356 scope.$watch(watchExpression, watchAction, isOneTime); 26357 26358 function addClasses(classString) { 26359 classString = digestClassCounts(split(classString), 1); 26360 attr.$addClass(classString); 26361 } 26362 26363 function removeClasses(classString) { 26364 classString = digestClassCounts(split(classString), -1); 26365 attr.$removeClass(classString); 26366 } 26367 26368 function updateClasses(oldClassString, newClassString) { 26369 var oldClassArray = split(oldClassString); 26370 var newClassArray = split(newClassString); 26371 26372 var toRemoveArray = arrayDifference(oldClassArray, newClassArray); 26373 var toAddArray = arrayDifference(newClassArray, oldClassArray); 26374 26375 var toRemoveString = digestClassCounts(toRemoveArray, -1); 26376 var toAddString = digestClassCounts(toAddArray, 1); 26377 26378 attr.$addClass(toAddString); 26379 attr.$removeClass(toRemoveString); 26380 } 26381 26382 function digestClassCounts(classArray, count) { 26383 var classesToUpdate = []; 26384 26385 forEach(classArray, function(className) { 26386 if (count > 0 || classCounts[className]) { 26387 classCounts[className] = (classCounts[className] || 0) + count; 26388 if (classCounts[className] === +(count > 0)) { 26389 classesToUpdate.push(className); 26390 } 26391 } 26392 }); 26393 26394 return classesToUpdate.join(' '); 26395 } 26396 26397 function ngClassIndexWatchAction(newModulo) { 26398 // This watch-action should run before the `ngClass[OneTime]WatchAction()`, thus it 26399 // adds/removes `oldClassString`. If the `ngClass` expression has changed as well, the 26400 // `ngClass[OneTime]WatchAction()` will update the classes. 26401 if (newModulo === selector) { 26402 addClasses(oldClassString); 26403 } else { 26404 removeClasses(oldClassString); 26405 } 26406 26407 oldModulo = newModulo; 26408 } 26409 26410 function ngClassOneTimeWatchAction(newClassValue) { 26411 var newClassString = toClassString(newClassValue); 26412 26413 if (newClassString !== oldClassString) { 26414 ngClassWatchAction(newClassString); 26415 } 26416 } 26417 26418 function ngClassWatchAction(newClassString) { 26419 if (oldModulo === selector) { 26420 updateClasses(oldClassString, newClassString); 26421 } 26422 26423 oldClassString = newClassString; 26424 } 26425 } 26426 }; 26427 }]; 26428 26429 // Helpers 26430 function arrayDifference(tokens1, tokens2) { 26431 if (!tokens1 || !tokens1.length) return []; 26432 if (!tokens2 || !tokens2.length) return tokens1; 26433 26434 var values = []; 26435 26436 outer: 26437 for (var i = 0; i < tokens1.length; i++) { 26438 var token = tokens1[i]; 26439 for (var j = 0; j < tokens2.length; j++) { 26440 if (token === tokens2[j]) continue outer; 26441 } 26442 values.push(token); 26443 } 26444 26445 return values; 26446 } 26447 26448 function split(classString) { 26449 return classString && classString.split(' '); 26450 } 26451 26452 function toClassString(classValue) { 26453 var classString = classValue; 26454 26455 if (isArray(classValue)) { 26456 classString = classValue.map(toClassString).join(' '); 26457 } else if (isObject(classValue)) { 26458 classString = Object.keys(classValue). 26459 filter(function(key) { return classValue[key]; }). 26460 join(' '); 26461 } 26462 26463 return classString; 26464 } 26465
26466 function toFlatValue(classValue) { 26467 var flatValue = classValue; 26468 26469 if (isArray(classValue)) { 26470 flatValue = classValue.map(toFlatValue); 26471 } else if (isObject(classValue)) { 26472 var hasUndefined = false; 26473 26474 flatValue = Object.keys(classValue).filter(function(key) { 26475 var value = classValue[key]; 26476 26477 if (!hasUndefined && isUndefined(value)) { 26478 hasUndefined = true; 26479 } 26480 26481 return value; 26482 }); 26483 26484 if (hasUndefined) { 26485 // Prevent the `oneTimeLiteralWatchInterceptor` from unregistering 26486 // the watcher, by including at least one `undefined` value. 26487 flatValue.push(undefined); 26488 } 26489 } 26490 26491 return flatValue; 26492 } 26493} 26494 26495/** 26496 * @ngdoc directive 26497 * @name ngClass 26498 * @restrict AC 26499 * 26500 * @description 26501 * The `ngClass` directive allows you to dynamically set CSS classes on an HTML element by databinding 26502 * an expression that represents all classes to be added. 26503 * 26504 * The directive operates in three different ways, depending on which of three types the expression 26505 * evaluates to: 26506 * 26507 * 1. If the expression evaluates to a string, the string should be one or more space-delimited class 26508 * names. 26509 * 26510 * 2. If the expression evaluates to an object, then for each key-value pair of the 26511 * object with a truthy value the corresponding key is used as a class name. 26512 * 26513 * 3. If the expression evaluates to an array, each element of the array should either be a string as in 26514 * type 1 or an object as in type 2. This means that you can mix strings and objects together in an array 26515 * to give you more control over what CSS classes appear. See the code below for an example of this. 26516 * 26517 * 26518 * The directive won't add duplicate classes if a particular class was already set. 26519 * 26520 * When the expression changes, the previously added classes are removed and only then are the 26521 * new classes added. 26522 * 26523 * @knownIssue 26524 * You should not use {@link guide/interpolation interpolation} in the value of the `class` 26525 * attribute, when using the `ngClass` directive on the same element. 26526 * See {@link guide/interpolation#known-issues here} for more info. 26527 * 26528 * @animations 26529 * | Animation | Occurs | 26530 * |----------------------------------|-------------------------------------| 26531 * | {@link ng.$animate#addClass addClass} | just before the class is applied to the element | 26532 * | {@link ng.$animate#removeClass removeClass} | just before the class is removed from the element | 26533 * 26534 * @element ANY 26535 * @param {expression} ngClass {@link guide/expression Expression} to eval. The result 26536 * of the evaluation can be a string representing space delimited class 26537 * names, an array, or a map of class names to boolean values. In the case of a map, the 26538 * names of the properties whose values are truthy will be added as css classes to the 26539 * element. 26540 * 26541 * @example Example that demonstrates basic bindings via ngClass directive. 26542 <example name="ng-class"> 26543 <file name="index.html"> 26544 <p ng-class="{strike: deleted, bold: important, 'has-error': error}">Map Syntax Example</p> 26545 <label> 26546 <input type="checkbox" ng-model="deleted"> 26547 deleted (apply "strike" class) 26548 </label><br> 26549 <label> 26550 <input type="checkbox" ng-model="important"> 26551 important (apply "bold" class) 26552 </label><br> 26553 <label> 26554 <input type="checkbox" ng-model="error"> 26555 error (apply "has-error" class) 26556 </label> 26557 <hr> 26558 <p ng-class="style">Using String Syntax</p> 26559 <input type="text" ng-model="style" 26560 placeholder="Type: bold strike red" aria-label="Type: bold strike red"> 26561 <hr> 26562 <p ng-class="[style1, style2, style3]">Using Array Syntax</p> 26563 <input ng-model="style1" 26564 placeholder="Type: bold, strike or red" aria-label="Type: bold, strike or red"><br> 26565 <input ng-model="style2" 26566 placeholder="Type: bold, strike or red" aria-label="Type: bold, strike or red 2"><br> 26567 <input ng-model="style3" 26568 placeholder="Type: bold, strike or red" aria-label="Type: bold, strike or red 3"><br> 26569 <hr> 26570 <p ng-class="[style4, {orange: warning}]">Using Array and Map Syntax</p> 26571 <input ng-model="style4" placeholder="Type: bold, strike" aria-label="Type: bold, strike"><br> 26572 <label><input type="checkbox" ng-model="warning"> warning (apply "orange" class)</label> 26573 </file> 26574 <file name="style.css"> 26575 .strike { 26576 text-decoration: line-through; 26577 } 26578 .bold { 26579 font-weight: bold; 26580 } 26581 .red { 26582 color: red; 26583 } 26584 .has-error { 26585 color: red; 26586 background-color: yellow; 26587 } 26588 .orange { 26589 color: orange; 26590 } 26591 </file> 26592 <file name="protractor.js" type="protractor"> 26593 var ps = element.all(by.css('p')); 26594 26595 it('should let you toggle the class', function() { 26596 26597 expect(ps.first().getAttribute('class')).not.toMatch(/bold/); 26598 expect(ps.first().getAttribute('class')).not.toMatch(/has-error/); 26599
26600 element(by.model('important')).click(); 26601 expect(ps.first().getAttribute('class')).toMatch(/bold/); 26602 26603 element(by.model('error')).click(); 26604 expect(ps.first().getAttribute('class')).toMatch(/has-error/); 26605 }); 26606 26607 it('should let you toggle string example', function() { 26608 expect(ps.get(1).getAttribute('class')).toBe(''); 26609 element(by.model('style')).clear(); 26610 element(by.model('style')).sendKeys('red'); 26611 expect(ps.get(1).getAttribute('class')).toBe('red'); 26612 }); 26613 26614 it('array example should have 3 classes', function() { 26615 expect(ps.get(2).getAttribute('class')).toBe(''); 26616 element(by.model('style1')).sendKeys('bold'); 26617 element(by.model('style2')).sendKeys('strike'); 26618 element(by.model('style3')).sendKeys('red'); 26619 expect(ps.get(2).getAttribute('class')).toBe('bold strike red'); 26620 }); 26621 26622 it('array with map example should have 2 classes', function() { 26623 expect(ps.last().getAttribute('class')).toBe(''); 26624 element(by.model('style4')).sendKeys('bold'); 26625 element(by.model('warning')).click(); 26626 expect(ps.last().getAttribute('class')).toBe('bold orange'); 26627 }); 26628 </file> 26629 </example> 26630 26631 ## Animations 26632 26633 The example below demonstrates how to perform animations using ngClass. 26634 26635 <example module="ngAnimate" deps="angular-animate.js" animations="true" name="ng-class"> 26636 <file name="index.html"> 26637 <input id="setbtn" type="button" value="set" ng-click="myVar='my-class'"> 26638 <input id="clearbtn" type="button" value="clear" ng-click="myVar=''"> 26639 <br> 26640 <span class="base-class" ng-class="myVar">Sample Text</span> 26641 </file> 26642 <file name="style.css"> 26643 .base-class { 26644 transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s; 26645 } 26646 26647 .base-class.my-class { 26648 color: red; 26649 font-size:3em; 26650 } 26651 </file> 26652 <file name="protractor.js" type="protractor"> 26653 it('should check ng-class', function() { 26654 expect(element(by.css('.base-class')).getAttribute('class')).not. 26655 toMatch(/my-class/); 26656 26657 element(by.id('setbtn')).click(); 26658 26659 expect(element(by.css('.base-class')).getAttribute('class')). 26660 toMatch(/my-class/); 26661 26662 element(by.id('clearbtn')).click(); 26663 26664 expect(element(by.css('.base-class')).getAttribute('class')).not. 26665 toMatch(/my-class/); 26666 }); 26667 </file> 26668 </example> 26669 26670 26671 ## ngClass and pre-existing CSS3 Transitions/Animations 26672 The ngClass directive still supports CSS3 Transitions/Animations even if they do not follow the ngAnimate CSS naming structure. 26673 Upon animation ngAnimate will apply supplementary CSS classes to track the start and end of an animation, but this will not hinder 26674 any pre-existing CSS transitions already on the element. To get an idea of what happens during a class-based animation, be sure 26675 to view the step by step details of {@link $animate#addClass $animate.addClass} and 26676 {@link $animate#removeClass $animate.removeClass}. 26677 */ 26678var ngClassDirective = classDirective('', true); 26679 26680/** 26681 * @ngdoc directive 26682 * @name ngClassOdd 26683 * @restrict AC 26684 * 26685 * @description 26686 * The `ngClassOdd` and `ngClassEven` directives work exactly as 26687 * {@link ng.directive:ngClass ngClass}, except they work in 26688 * conjunction with `ngRepeat` and take effect only on odd (even) rows. 26689 * 26690 * This directive can be applied only within the scope of an 26691 * {@link ng.directive:ngRepeat ngRepeat}. 26692 * 26693 * @element ANY 26694 * @param {expression} ngClassOdd {@link guide/expression Expression} to eval. The result 26695 * of the evaluation can be a string representing space delimited class names or an array. 26696 * 26697 * @example 26698 <example name="ng-class-odd"> 26699 <file name="index.html"> 26700 <ol ng-init="names=['John', 'Mary', 'Cate', 'Suz']"> 26701 <li ng-repeat="name in names"> 26702 <span ng-class-odd="'odd'" ng-class-even="'even'"> 26703 {{name}} 26704 </span> 26705 </li> 26706 </ol> 26707 </file> 26708 <file name="style.css"> 26709 .odd { 26710 color: red; 26711 } 26712 .even { 26713 color: blue; 26714 } 26715 </file> 26716 <file name="protractor.js" type="protractor"> 26717 it('should check ng-class-odd and ng-class-even', function() { 26718 expect(element(by.repeater('name in names').row(0).column('name')).getAttribute('class')). 26719 toMatch(/odd/); 26720 expect(element(by.repeater('name in names').row(1).column('name')).getAttribute('class')). 26721 toMatch(/even/); 26722 }); 26723 </file> 26724 </example> 26725 */ 26726var ngClassOddDirective = classDirective('Odd', 0); 26727 26728/** 26729 * @ngdoc directive 26730 * @name ngClassEven 26731 * @restrict AC 26732 * 26733 * @description 26734 * The `ngClassOdd` and `ngClassEven` directives work exactly as 26735 * {@link ng.directive:ngClass ngClass}, except they work in 26736 * conjunction with `ngRepeat` and take effect only on odd (even) rows. 26737 * 26738 * This directive can be applied only within the scope of an 26739 * {@link ng.directive:ngRepeat ngRepeat}. 26740 * 26741 * @element ANY 26742 * @param {expression} ngClassEven {@link guide/expression Expression} to eval. The 26743 * result of the evaluation can be a string representing space delimited class names or an array.
26744 * 26745 * @example 26746 <example name="ng-class-even"> 26747 <file name="index.html"> 26748 <ol ng-init="names=['John', 'Mary', 'Cate', 'Suz']"> 26749 <li ng-repeat="name in names"> 26750 <span ng-class-odd="'odd'" ng-class-even="'even'"> 26751 {{name}} 26752 </span> 26753 </li> 26754 </ol> 26755 </file> 26756 <file name="style.css"> 26757 .odd { 26758 color: red; 26759 } 26760 .even { 26761 color: blue; 26762 } 26763 </file> 26764 <file name="protractor.js" type="protractor"> 26765 it('should check ng-class-odd and ng-class-even', function() { 26766 expect(element(by.repeater('name in names').row(0).column('name')).getAttribute('class')). 26767 toMatch(/odd/); 26768 expect(element(by.repeater('name in names').row(1).column('name')).getAttribute('class')). 26769 toMatch(/even/); 26770 }); 26771 </file> 26772 </example> 26773 */ 26774var ngClassEvenDirective = classDirective('Even', 1); 26775 26776/** 26777 * @ngdoc directive 26778 * @name ngCloak 26779 * @restrict AC 26780 * 26781 * @description 26782 * The `ngCloak` directive is used to prevent the Angular html template from being briefly 26783 * displayed by the browser in its raw (uncompiled) form while your application is loading. Use this 26784 * directive to avoid the undesirable flicker effect caused by the html template display. 26785 * 26786 * The directive can be applied to the `<body>` element, but the preferred usage is to apply 26787 * multiple `ngCloak` directives to small portions of the page to permit progressive rendering 26788 * of the browser view. 26789 * 26790 * `ngCloak` works in cooperation with the following css rule embedded within `angular.js` and 26791 * `angular.min.js`. 26792 * For CSP mode please add `angular-csp.css` to your html file (see {@link ng.directive:ngCsp ngCsp}). 26793 * 26794 * ```css 26795 * [ng\:cloak], [ng-cloak], [data-ng-cloak], [x-ng-cloak], .ng-cloak, .x-ng-cloak { 26796 * display: none !important; 26797 * } 26798 * ``` 26799 * 26800 * When this css rule is loaded by the browser, all html elements (including their children) that 26801 * are tagged with the `ngCloak` directive are hidden. When Angular encounters this directive 26802 * during the compilation of the template it deletes the `ngCloak` element attribute, making 26803 * the compiled element visible. 26804 * 26805 * For the best result, the `angular.js` script must be loaded in the head section of the html 26806 * document; alternatively, the css rule above must be included in the external stylesheet of the 26807 * application. 26808 * 26809 * @element ANY 26810 * 26811 * @example 26812 <example name="ng-cloak"> 26813 <file name="index.html"> 26814 <div id="template1" ng-cloak>{{ 'hello' }}</div> 26815 <div id="template2" class="ng-cloak">{{ 'world' }}</div> 26816 </file> 26817 <file name="protractor.js" type="protractor"> 26818 it('should remove the template directive and css class', function() { 26819 expect($('#template1').getAttribute('ng-cloak')). 26820 toBeNull(); 26821 expect($('#template2').getAttribute('ng-cloak')). 26822 toBeNull(); 26823 }); 26824 </file> 26825 </example> 26826 * 26827 */ 26828var ngCloakDirective = ngDirective({ 26829 compile: function(element, attr) { 26830 attr.$set('ngCloak', undefined); 26831 element.removeClass('ng-cloak'); 26832 } 26833}); 26834 26835/** 26836 * @ngdoc directive 26837 * @name ngController 26838 * 26839 * @description 26840 * The `ngController` directive attaches a controller class to the view. This is a key aspect of how angular 26841 * supports the principles behind the Model-View-Controller design pattern. 26842 * 26843 * MVC components in angular: 26844 * 26845 * * Model — Models are the properties of a scope; scopes are attached to the DOM where scope properties 26846 * are accessed through bindings. 26847 * * View — The template (HTML with data bindings) that is rendered into the View. 26848 * * Controller — The `ngController` directive specifies a Controller class; the class contains business 26849 * logic behind the application to decorate the scope with functions and values 26850 * 26851 * Note that you can also attach controllers to the DOM by declaring it in a route definition 26852 * via the {@link ngRoute.$route $route} service. A common mistake is to declare the controller 26853 * again using `ng-controller` in the template itself. This will cause the controller to be attached 26854 * and executed twice. 26855 * 26856 * @element ANY 26857 * @scope 26858 * @priority 500 26859 * @param {expression} ngController Name of a constructor function registered with the current 26860 * {@link ng.$controllerProvider $controllerProvider} or an {@link guide/expression expression} 26861 * that on the current scope evaluates to a constructor function. 26862 * 26863 * The controller instance can be published into a scope property by specifying 26864 * `ng-controller="as propertyName"`. 26865 * 26866 * If the current `$controllerProvider` is configured to use globals (via 26867 * {@link ng.$controllerProvider#allowGlobals `$controllerProvider.allowGlobals()` }), this may 26868 * also be the name of a globally accessible constructor function (deprecated, not recommended). 26869 * 26870 * @example 26871 * Here is a simple form for editing user contact information. Adding, remov
26871ing, clearing, and 26872 * greeting are methods declared on the controller (see source tab). These methods can 26873 * easily be called from the angular markup. Any changes to the data are automatically reflected 26874 * in the View without the need for a manual update. 26875 * 26876 * Two different declaration styles are included below: 26877 * 26878 * * one binds methods and properties directly onto the controller using `this`: 26879 * `ng-controller="SettingsController1 as settings"` 26880 * * one injects `$scope` into the controller: 26881 * `ng-controller="SettingsController2"` 26882 * 26883 * The second option is more common in the Angular community, and is generally used in boilerplates 26884 * and in this guide. However, there are advantages to binding properties directly to the controller 26885 * and avoiding scope. 26886 * 26887 * * Using `controller as` makes it obvious which controller you are accessing in the template when 26888 * multiple controllers apply to an element. 26889 * * If you are writing your controllers as classes you have easier access to the properties and 26890 * methods, which will appear on the scope, from inside the controller code. 26891 * * Since there is always a `.` in the bindings, you don't have to worry about prototypal 26892 * inheritance masking primitives. 26893 * 26894 * This example demonstrates the `controller as` syntax. 26895 * 26896 * <example name="ngControllerAs" module="controllerAsExample"> 26897 * <file name="index.html"> 26898 * <div id="ctrl-as-exmpl" ng-controller="SettingsController1 as settings"> 26899 * <label>Name: <input type="text" ng-model="settings.name"/></label> 26900 * <button ng-click="settings.greet()">greet</button><br/> 26901 * Contact: 26902 * <ul> 26903 * <li ng-repeat="contact in settings.contacts"> 26904 * <select ng-model="contact.type" aria-label="Contact method" id="select_{{$index}}"> 26905 * <option>phone</option> 26906 * <option>email</option> 26907 * </select> 26908 * <input type="text" ng-model="contact.value" aria-labelledby="select_{{$index}}" /> 26909 * <button ng-click="settings.clearContact(contact)">clear</button> 26910 * <button ng-click="settings.removeContact(contact)" aria-label="Remove">X</button> 26911 * </li> 26912 * <li><button ng-click="settings.addContact()">add</button></li> 26913 * </ul> 26914 * </div> 26915 * </file> 26916 * <file name="app.js"> 26917 * angular.module('controllerAsExample', []) 26918 * .controller('SettingsController1', SettingsController1); 26919 * 26920 * function SettingsController1() { 26921 * this.name = 'John Smith'; 26922 * this.contacts = [ 26923 * {type: 'phone', value: '408 555 1212'}, 26924 * {type: 'email', value: '[email protected]'} 26925 * ]; 26926 * } 26927 * 26928 * SettingsController1.prototype.greet = function() { 26929 * alert(this.name); 26930 * }; 26931 * 26932 * SettingsController1.prototype.addContact = function() { 26933 * this.contacts.push({type: 'email', value: '[email protected]'}); 26934 * }; 26935 * 26936 * SettingsController1.prototype.removeContact = function(contactToRemove) { 26937 * var index = this.contacts.indexOf(contactToRemove); 26938 * this.contacts.splice(index, 1); 26939 * }; 26940 * 26941 * SettingsController1.prototype.clearContact = function(contact) { 26942 * contact.type = 'phone'; 26943 * contact.value = ''; 26944 * }; 26945 * </file> 26946 * <file name="protractor.js" type="protractor"> 26947 * it('should check controller as', function() { 26948 * var container = element(by.id('ctrl-as-exmpl')); 26949 * expect(container.element(by.model('settings.name')) 26950 * .getAttribute('value')).toBe('John Smith'); 26951 * 26952 * var firstRepeat = 26953 * container.element(by.repeater('contact in settings.contacts').row(0)); 26954 * var secondRepeat = 26955 * container.element(by.repeater('contact in settings.contacts').row(1)); 26956 * 26957 * expect(firstRepeat.element(by.model('contact.value')).getAttribute('value')) 26958 * .toBe('408 555 1212'); 26959 * 26960 * expect(secondRepeat.element(by.model('contact.value')).getAttribute('value')) 26961 * .toBe('[email protected]'); 26962 * 26963 * firstRepeat.element(by.buttonText('clear')).click(); 26964 * 26965 * expect(firstRepeat.element(by.model('contact.value')).getAttribute('value')) 26966 * .toBe(''); 26967 * 26968 * container.element(by.buttonText('add')).click(); 26969 * 26970 * expect(container.element(by.repeater('contact in settings.contacts').row(2)) 26971 * .element(by.model('contact.value')) 26972 * .getAttribute('value')) 26973 * .toBe('[email protected]'); 26974 * }); 26975 * </file> 26976 * </example> 26977 * 26978 * This example demonstrates the "attach to `$scope`" style of controller. 26979 * 26980 * <example name="ngController" module="controllerExample"> 26981 * <file name="index.html"> 26982 * <div id="ctrl-exmpl" ng-controller="SettingsController2"> 26983 * <label>Name: <input type="text" ng-model="name"/></label> 26984 * <button ng-click="greet()">greet</button><br/> 26985 * Contact: 26986 * <ul> 26987 * <li ng-repeat="contact in contacts"> 26988 * <select ng-model="contact.type" id="select_{{$index}}"> 26989 * <option>phone</option> 26990 * <option>email</option> 26991 * </select> 26992 * <input type="text" ng-model="contact.value" aria-labelledby="select_{{$index}}" /> 26993 * <button ng-click="clearContact(contact)">clear</button> 26994 * <button ng-click="removeContact(contact)">X</button> 26995 * </li> 26996 * <li>[ <button ng-click="addContact()">add</button> ]</li> 26997 * </ul> 26998 * </div> 26999 * </file> 27000 * <file name="app.js">
27001 * angular.module('controllerExample', []) 27002 * .controller('SettingsController2', ['$scope', SettingsController2]); 27003 * 27004 * function SettingsController2($scope) { 27005 * $scope.name = 'John Smith'; 27006 * $scope.contacts = [ 27007 * {type:'phone', value:'408 555 1212'}, 27008 * {type:'email', value:'[email protected]'} 27009 * ]; 27010 * 27011 * $scope.greet = function() { 27012 * alert($scope.name); 27013 * }; 27014 * 27015 * $scope.addContact = function() { 27016 * $scope.contacts.push({type:'email', value:'[email protected]'}); 27017 * }; 27018 * 27019 * $scope.removeContact = function(contactToRemove) { 27020 * var index = $scope.contacts.indexOf(contactToRemove); 27021 * $scope.contacts.splice(index, 1); 27022 * }; 27023 * 27024 * $scope.clearContact = function(contact) { 27025 * contact.type = 'phone'; 27026 * contact.value = ''; 27027 * }; 27028 * } 27029 * </file> 27030 * <file name="protractor.js" type="protractor"> 27031 * it('should check controller', function() { 27032 * var container = element(by.id('ctrl-exmpl')); 27033 * 27034 * expect(container.element(by.model('name')) 27035 * .getAttribute('value')).toBe('John Smith'); 27036 * 27037 * var firstRepeat = 27038 * container.element(by.repeater('contact in contacts').row(0)); 27039 * var secondRepeat = 27040 * container.element(by.repeater('contact in contacts').row(1)); 27041 * 27042 * expect(firstRepeat.element(by.model('contact.value')).getAttribute('value')) 27043 * .toBe('408 555 1212'); 27044 * expect(secondRepeat.element(by.model('contact.value')).getAttribute('value')) 27045 * .toBe('[email protected]'); 27046 * 27047 * firstRepeat.element(by.buttonText('clear')).click(); 27048 * 27049 * expect(firstRepeat.element(by.model('contact.value')).getAttribute('value')) 27050 * .toBe(''); 27051 * 27052 * container.element(by.buttonText('add')).click(); 27053 * 27054 * expect(container.element(by.repeater('contact in contacts').row(2)) 27055 * .element(by.model('contact.value')) 27056 * .getAttribute('value')) 27057 * .toBe('[email protected]'); 27058 * }); 27059 * </file> 27060 *</example> 27061 27062 */ 27063var ngControllerDirective = [function() { 27064 return { 27065 restrict: 'A', 27066 scope: true, 27067 controller: '@', 27068 priority: 500 27069 }; 27070}]; 27071 27072/** 27073 * @ngdoc directive 27074 * @name ngCsp 27075 * 27076 * @restrict A 27077 * @element ANY 27078 * @description 27079 * 27080 * Angular has some features that can conflict with certain restrictions that are applied when using 27081 * [CSP (Content Security Policy)](https://developer.mozilla.org/en/Security/CSP) rules. 27082 * 27083 * If you intend to implement CSP with these rules then you must tell Angular not to use these 27084 * features. 27085 * 27086 * This is necessary when developing things like Google Chrome Extensions or Universal Windows Apps. 27087 * 27088 * 27089 * The following default rules in CSP affect Angular: 27090 * 27091 * * The use of `eval()`, `Function(string)` and similar functions to dynamically create and execute 27092 * code from strings is forbidden. Angular makes use of this in the {@link $parse} service to 27093 * provide a 30% increase in the speed of evaluating Angular expressions. (This CSP rule can be 27094 * disabled with the CSP keyword `unsafe-eval`, but it is generally not recommended as it would 27095 * weaken the protections offered by CSP.) 27096 * 27097 * * The use of inline resources, such as inline `<script>` and `<style>` elements, are forbidden. 27098 * This prevents apps from injecting custom styles directly into the document. Angular makes use of 27099 * this to include some CSS rules (e.g. {@link ngCloak} and {@link ngHide}). To make these 27100 * directives work when a CSP rule is blocking inline styles, you must link to the `angular-csp.css` 27101 * in your HTML manually. (This CSP rule can be disabled with the CSP keyword `unsafe-inline`, but 27102 * it is generally not recommended as it would weaken the protections offered by CSP.) 27103 * 27104 * If you do not provide `ngCsp` then Angular tries to autodetect if CSP is blocking dynamic code 27105 * creation from strings (e.g., `unsafe-eval` not specified in CSP header) and automatically 27106 * deactivates this feature in the {@link $parse} service. This autodetection, however, triggers a 27107 * CSP error to be logged in the console: 27108 * 27109 * ``` 27110 * Refused to evaluate a string as JavaScript because 'unsafe-eval' is not an allowed source of 27111 * script in the following Content Security Policy directive: "default-src 'self'". Note that 27112 * 'script-src' was not explicitly set, so 'default-src' is used as a fallback. 27113 * ``` 27114 * 27115 * This error is harmless but annoying. To prevent the error from showing up, put the `ngCsp` 27116 * directive on an element of the HTML document that appears before the `<script>` tag that loads 27117 * the `angular.js` file. 27118 * 27119 * *Note: This directive is only available in the `ng-csp` and `data-ng-csp` attribute form.* 27120 * 27121 * You can specify which of the CSP related Angular features should be deactivated by providing 27122 * a value for the `ng-csp` attribute. The options are as follows: 27123 * 27124 * * no-inline-style: this stops Angular from injecting CSS styles into the DOM 27125 *
27126 * * no-unsafe-eval: this stops Angular from optimizing $parse with unsafe eval of strings 27127 * 27128 * You can use these values in the following combinations: 27129 * 27130 * 27131 * * No declaration means that Angular will assume that you can do inline styles, but it will do 27132 * a runtime check for unsafe-eval. E.g. `<body>`. This is backwardly compatible with previous 27133 * versions of Angular. 27134 * 27135 * * A simple `ng-csp` (or `data-ng-csp`) attribute will tell Angular to deactivate both inline 27136 * styles and unsafe eval. E.g. `<body ng-csp>`. This is backwardly compatible with previous 27137 * versions of Angular. 27138 * 27139 * * Specifying only `no-unsafe-eval` tells Angular that we must not use eval, but that we can 27140 * inject inline styles. E.g. `<body ng-csp="no-unsafe-eval">`. 27141 * 27142 * * Specifying only `no-inline-style` tells Angular that we must not inject styles, but that we can 27143 * run eval - no automatic check for unsafe eval will occur. E.g. `<body ng-csp="no-inline-style">` 27144 * 27145 * * Specifying both `no-unsafe-eval` and `no-inline-style` tells Angular that we must not inject 27146 * styles nor use eval, which is the same as an empty: ng-csp. 27147 * E.g.`<body ng-csp="no-inline-style;no-unsafe-eval">` 27148 * 27149 * @example 27150 * This example shows how to apply the `ngCsp` directive to the `html` tag. 27151 ```html 27152 <!doctype html> 27153 <html ng-app ng-csp> 27154 ... 27155 ... 27156 </html> 27157 ``` 27158 * @example 27159 <!-- Note: the `.csp` suffix in the example name triggers CSP mode in our http server! --> 27160 <example name="example.csp" module="cspExample" ng-csp="true"> 27161 <file name="index.html"> 27162 <div ng-controller="MainController as ctrl"> 27163 <div> 27164 <button ng-click="ctrl.inc()" id="inc">Increment</button> 27165 <span id="counter"> 27166 {{ctrl.counter}} 27167 </span> 27168 </div> 27169 27170 <div> 27171 <button ng-click="ctrl.evil()" id="evil">Evil</button> 27172 <span id="evilError"> 27173 {{ctrl.evilError}} 27174 </span> 27175 </div> 27176 </div> 27177 </file> 27178 <file name="script.js"> 27179 angular.module('cspExample', []) 27180 .controller('MainController', function MainController() { 27181 this.counter = 0; 27182 this.inc = function() { 27183 this.counter++; 27184 }; 27185 this.evil = function() { 27186 try { 27187 eval('1+2'); // eslint-disable-line no-eval 27188 } catch (e) { 27189 this.evilError = e.message; 27190 } 27191 }; 27192 }); 27193 </file> 27194 <file name="protractor.js" type="protractor"> 27195 var util, webdriver; 27196 27197 var incBtn = element(by.id('inc')); 27198 var counter = element(by.id('counter')); 27199 var evilBtn = element(by.id('evil')); 27200 var evilError = element(by.id('evilError')); 27201 27202 function getAndClearSevereErrors() { 27203 return browser.manage().logs().get('browser').then(function(browserLog) { 27204 return browserLog.filter(function(logEntry) { 27205 return logEntry.level.value > webdriver.logging.Level.WARNING.value; 27206 }); 27207 }); 27208 } 27209 27210 function clearErrors() { 27211 getAndClearSevereErrors(); 27212 } 27213 27214 function expectNoErrors() { 27215 getAndClearSevereErrors().then(function(filteredLog) { 27216 expect(filteredLog.length).toEqual(0); 27217 if (filteredLog.length) { 27218 console.log('browser console errors: ' + util.inspect(filteredLog)); 27219 } 27220 }); 27221 } 27222 27223 function expectError(regex) { 27224 getAndClearSevereErrors().then(function(filteredLog) { 27225 var found = false; 27226 filteredLog.forEach(function(log) { 27227 if (log.message.match(regex)) { 27228 found = true; 27229 } 27230 }); 27231 if (!found) { 27232 throw new Error('expected an error that matches ' + regex); 27233 } 27234 }); 27235 } 27236 27237 beforeEach(function() { 27238 util = require('util'); 27239 webdriver = require('selenium-webdriver'); 27240 }); 27241 27242 // For now, we only test on Chrome, 27243 // as Safari does not load the page with Protractor's injected scripts, 27244 // and Firefox webdriver always disables content security policy (#6358) 27245 if (browser.params.browser !== 'chrome') { 27246 return; 27247 } 27248 27249 it('should not report errors when the page is loaded', function() { 27250 // clear errors so we are not dependent on previous tests 27251 clearErrors(); 27252 // Need to reload the page as the page is already loaded when 27253 // we come here 27254 browser.driver.getCurrentUrl().then(function(url) { 27255 browser.get(url); 27256 }); 27257 expectNoErrors(); 27258 }); 27259 27260 it('should evaluate expressions', function() { 27261 expect(counter.getText()).toEqual('0'); 27262 incBtn.click(); 27263 expect(counter.getText()).toEqual('1'); 27264 expectNoErrors(); 27265 }); 27266 27267 it('should throw and report an error when using "eval"', function() { 27268 evilBtn.click(); 27269 expect(evilError.getText()).toMatch(/Content Security Policy/); 27270 expectError(/Content Security Policy/); 27271 }); 27272 </file> 27273 </example> 27274 */ 27275 27276// `ngCsp` is not implemented as a proper directive any more, because we need it be processed while 27277// we bootstrap the app (before `$parse` is instantiated). For this reason, we just have the `csp()` 27278// fn that looks for the `ng-csp` attribute anywhere in the current doc. 27279 27280/** 27281 * @ngdoc directive 27282 * @name ngClick 27283 * 27284 * @description 27285 * The ngClick directive allows you to specify custom behavior when 27286 * an element is clicked. 27287 * 27288 * @element ANY 27289 * @priority 0 27290 * @param {expression} ngClick {@link guide/expression Expression} to evaluate upon 27291 * click. ({@link guide/expression#-event- Event object is available as `$event`}) 27292 * 27293 * @example 27294 <example name="ng-click"> 27295 <file name="index.html"> 27296 <button ng-click="count = count + 1" ng-init="count=0"> 27297 Increment 27298 </button>
27299 <span> 27300 count: {{count}} 27301 </span> 27302 </file> 27303 <file name="protractor.js" type="protractor"> 27304 it('should check ng-click', function() { 27305 expect(element(by.binding('count')).getText()).toMatch('0'); 27306 element(by.css('button')).click(); 27307 expect(element(by.binding('count')).getText()).toMatch('1'); 27308 }); 27309 </file> 27310 </example> 27311 */ 27312/* 27313 * A collection of directives that allows creation of custom event handlers that are defined as 27314 * angular expressions and are compiled and executed within the current scope. 27315 */ 27316var ngEventDirectives = {}; 27317 27318// For events that might fire synchronously during DOM manipulation 27319// we need to execute their event handlers asynchronously using $evalAsync, 27320// so that they are not executed in an inconsistent state. 27321var forceAsyncEvents = { 27322 'blur': true, 27323 'focus': true 27324}; 27325forEach( 27326 'click dblclick mousedown mouseup mouseover mouseout mousemove mouseenter mouseleave keydown keyup keypress submit focus blur copy cut paste'.split(' '), 27327 function(eventName) { 27328 var directiveName = directiveNormalize('ng-' + eventName); 27329 ngEventDirectives[directiveName] = ['$parse', '$rootScope', function($parse, $rootScope) { 27330 return { 27331 restrict: 'A', 27332 compile: function($element, attr) { 27333 // NOTE: 27334 // We expose the powerful `$event` object on the scope that provides access to the Window, 27335 // etc. This is OK, because expressions are not sandboxed any more (and the expression 27336 // sandbox was never meant to be a security feature anyway). 27337 var fn = $parse(attr[directiveName]); 27338 return function ngEventHandler(scope, element) { 27339 element.on(eventName, function(event) { 27340 var callback = function() { 27341 fn(scope, {$event: event}); 27342 }; 27343 if (forceAsyncEvents[eventName] && $rootScope.$$phase) { 27344 scope.$evalAsync(callback); 27345 } else { 27346 scope.$apply(callback); 27347 } 27348 }); 27349 }; 27350 } 27351 }; 27352 }]; 27353 } 27354); 27355 27356/** 27357 * @ngdoc directive 27358 * @name ngDblclick 27359 * 27360 * @description 27361 * The `ngDblclick` directive allows you to specify custom behavior on a dblclick event. 27362 * 27363 * @element ANY 27364 * @priority 0 27365 * @param {expression} ngDblclick {@link guide/expression Expression} to evaluate upon 27366 * a dblclick. (The Event object is available as `$event`) 27367 * 27368 * @example 27369 <example name="ng-dblclick"> 27370 <file name="index.html"> 27371 <button ng-dblclick="count = count + 1" ng-init="count=0"> 27372 Increment (on double click) 27373 </button> 27374 count: {{count}} 27375 </file> 27376 </example> 27377 */ 27378 27379 27380/** 27381 * @ngdoc directive 27382 * @name ngMousedown 27383 * 27384 * @description 27385 * The ngMousedown directive allows you to specify custom behavior on mousedown event. 27386 * 27387 * @element ANY 27388 * @priority 0 27389 * @param {expression} ngMousedown {@link guide/expression Expression} to evaluate upon 27390 * mousedown. ({@link guide/expression#-event- Event object is available as `$event`}) 27391 * 27392 * @example 27393 <example name="ng-mousedown"> 27394 <file name="index.html"> 27395 <button ng-mousedown="count = count + 1" ng-init="count=0"> 27396 Increment (on mouse down) 27397 </button> 27398 count: {{count}} 27399 </file> 27400 </example> 27401 */ 27402 27403 27404/** 27405 * @ngdoc directive 27406 * @name ngMouseup 27407 * 27408 * @description 27409 * Specify custom behavior on mouseup event. 27410 * 27411 * @element ANY 27412 * @priority 0 27413 * @param {expression} ngMouseup {@link guide/expression Expression} to evaluate upon 27414 * mouseup. ({@link guide/expression#-event- Event object is available as `$event`}) 27415 * 27416 * @example 27417 <example name="ng-mouseup"> 27418 <file name="index.html"> 27419 <button ng-mouseup="count = count + 1" ng-init="count=0"> 27420 Increment (on mouse up) 27421 </button> 27422 count: {{count}} 27423 </file> 27424 </example> 27425 */ 27426 27427/** 27428 * @ngdoc directive 27429 * @name ngMouseover 27430 * 27431 * @description 27432 * Specify custom behavior on mouseover event. 27433 * 27434 * @element ANY 27435 * @priority 0 27436 * @param {expression} ngMouseover {@link guide/expression Expression} to evaluate upon 27437 * mouseover. ({@link guide/expression#-event- Event object is available as `$event`}) 27438 * 27439 * @example 27440 <example name="ng-mouseover"> 27441 <file name="index.html"> 27442 <button ng-mouseover="count = count + 1" ng-init="count=0"> 27443 Increment (when mouse is over) 27444 </button> 27445 count: {{count}} 27446 </file> 27447 </example> 27448 */ 27449 27450 27451/** 27452 * @ngdoc directive 27453 * @name ngMouseenter 27454 * 27455 * @description 27456 * Specify custom behavior on mouseenter event. 27457 * 27458 * @element ANY 27459 * @priority 0 27460 * @param {expression} ngMouseenter {@link guide/expression Expression} to evaluate upon 27461 * mouseenter. ({@link guide/expression#-event- Event object is available as `$event`}) 27462 * 27463 * @example 27464 <example name="ng-mouseenter"> 27465 <file name="index.html"> 27466 <button ng-mouseenter="count = count + 1" ng-init="count=0"> 27467 Increment (when mouse enters) 27468 </button> 27469 count: {{count}} 27470 </file> 27471 </example> 27472 */ 27473 27474 27475/** 27476 * @ngdoc directive 27477 * @name ngMouseleave 27478 * 27479 * @description 27480 * Specify custom behavior on mouseleave event. 27481 * 27482 * @element ANY 27483 * @priority 0 27484 * @param {expression} ngMouseleave {@link guide/expression Expression} to evaluate upon 27485 * mouseleave. ({@link guide/expression#-event- Event object is available as `$event`}) 27486 * 27487 * @example 27488 <example name="ng-mouseleave"> 27489 <file name="index.html"> 27490 <button ng-mouseleave="count = count + 1" ng-init="count=0"> 27491 Increment (when mouse leaves) 27492 </button> 27493 count: {{count}} 27494 </file> 27495 </example> 27496 */ 27497 27498 27499/** 27500 * @ngdoc directive 27501 * @name ngMousemove 27502 * 27503 * @description 27504 * Specify custom behavior on mousemove event. 27505 * 27506 * @element ANY 27507 * @priority 0 27508 * @param {expression} ngMousemove {@link guide/expression Expression} to evaluate upon 27509 * mousemove. ({@link guide/expression#-event- Event object is available as `$event`}) 27510 * 27511 * @example 27512 <example name="ng-mousemove"> 27513 <file name="index.html"> 27514 <button ng-mousemove="count = count + 1" ng-init="count=0"> 27515 Increment (when mouse moves) 27516 </button> 27517 count: {{count}} 27518 </file> 27519 </example> 27520 */ 27521 27522 27523/** 27524 * @ngdoc directive 27525 * @name ngKeydown 27526 * 27527 * @description 27528 * Specify custom behavior on keydown event. 27529 * 27530 * @element ANY 27531 * @priority 0 27532 * @param {expression} ngKeydown {@link guide/expression Expression} to evaluate upon 27533 * keydown. (Event object is available as `$event` and can be interrogated for keyCode, altKey, etc.) 27534 * 27535 * @example 27536 <example name="ng-keydown"> 27537 <file name="index.html"> 27538 <input ng-keydown="count = count + 1" ng-init="count=0"> 27539 key down count: {{count}} 27540 </file> 27541 </example> 27542 */ 27543 27544 27545/** 27546 * @ngdoc directive 27547 * @name ngKeyup 27548 * 27549 * @description 27550 * Specify custom behavior on keyup event. 27551 * 27552 * @element ANY 27553 * @priority 0 27554 * @param {expression} ngKeyup {@link guide/expression Expression} to evaluate upon 27555 * keyup. (Event object is available as `$event` and can be interrogated for keyCode, altKey, etc.) 27556 * 27557 * @example 27558 <example name="ng-keyup"> 27559 <file name="index.html"> 27560 <p>Typing in the input box below updates the key count</p> 27561 <input ng-keyup="count = count + 1" ng-init="count=0"> key up count: {{count}} 27562 27563 <p>Typing in the input box below updates the keycode</p> 27564 <input ng-keyup="event=$event"> 27565 <p>event keyCode: {{ event.keyCode }}</p> 27566 <p>event altKey: {{ event.altKey }}</p> 27567 </file> 27568 </example> 27569 */ 27570 27571 27572/** 27573 * @ngdoc directive 27574 * @name ngKeypress 27575 * 27576 * @description 27577 * Specify custom behavior on keypress event. 27578 * 27579 * @element ANY 27580 * @param {expression} ngKeypress {@link guide/expression Expression} to evaluate upon 27581 * keypress. ({@link guide/expression#-event- Event object is available as `$event`} 27582 * and can be interrogated for keyCode, altKey, etc.) 27583 * 27584 * @example 27585 <example name="ng-keypress"> 27586 <file name="index.html"> 27587 <input ng-keypress="count = count + 1" ng-init="count=0"> 27588 key press count: {{count}} 27589 </file> 27590 </example> 27591 */ 27592 27593 27594/** 27595 * @ngdoc directive 27596 * @name ngSubmit 27597 * 27598 * @description 27599 * Enables binding angular expressions to onsubmit events. 27600 * 27601 * Additionally it prevents the default action (which for form means
27601sending the request to the 27602 * server and reloading the current page), but only if the form does not contain `action`, 27603 * `data-action`, or `x-action` attributes. 27604 * 27605 * <div class="alert alert-warning"> 27606 * **Warning:** Be careful not to cause "double-submission" by using both the `ngClick` and 27607 * `ngSubmit` handlers together. See the 27608 * {@link form#submitting-a-form-and-preventing-the-default-action `form` directive documentation} 27609 * for a detailed discussion of when `ngSubmit` may be triggered. 27610 * </div> 27611 * 27612 * @element form 27613 * @priority 0 27614 * @param {expression} ngSubmit {@link guide/expression Expression} to eval. 27615 * ({@link guide/expression#-event- Event object is available as `$event`}) 27616 * 27617 * @example 27618 <example module="submitExample" name="ng-submit"> 27619 <file name="index.html"> 27620 <script> 27621 angular.module('submitExample', []) 27622 .controller('ExampleController', ['$scope', function($scope) { 27623 $scope.list = []; 27624 $scope.text = 'hello'; 27625 $scope.submit = function() { 27626 if ($scope.text) { 27627 $scope.list.push(this.text); 27628 $scope.text = ''; 27629 } 27630 }; 27631 }]); 27632 </script>
27633 <form ng-submit="submit()" ng-controller="ExampleController"> 27634 Enter text and hit enter: 27635 <input type="text" ng-model="text" name="text" /> 27636 <input type="submit" id="submit" value="Submit" /> 27637 <pre>list={{list}}</pre> 27638 </form> 27639 </file> 27640 <file name="protractor.js" type="protractor"> 27641 it('should check ng-submit', function() { 27642 expect(element(by.binding('list')).getText()).toBe('list=[]'); 27643 element(by.css('#submit')).click(); 27644 expect(element(by.binding('list')).getText()).toContain('hello'); 27645 expect(element(by.model('text')).getAttribute('value')).toBe(''); 27646 }); 27647 it('should ignore empty strings', function() { 27648 expect(element(by.binding('list')).getText()).toBe('list=[]'); 27649 element(by.css('#submit')).click(); 27650 element(by.css('#submit')).click(); 27651 expect(element(by.binding('list')).getText()).toContain('hello'); 27652 }); 27653 </file> 27654 </example> 27655 */ 27656 27657/** 27658 * @ngdoc directive 27659 * @name ngFocus 27660 * 27661 * @description 27662 * Specify custom behavior on focus event. 27663 * 27664 * Note: As the `focus` event is executed synchronously when calling `input.focus()` 27665 * AngularJS executes the expression using `scope.$evalAsync` if the event is fired 27666 * during an `$apply` to ensure a consistent state. 27667 * 27668 * @element window, input, select, textarea, a 27669 * @priority 0 27670 * @param {expression} ngFocus {@link guide/expression Expression} to evaluate upon 27671 * focus. ({@link guide/expression#-event- Event object is available as `$event`}) 27672 * 27673 * @example 27674 * See {@link ng.directive:ngClick ngClick} 27675 */ 27676 27677/** 27678 * @ngdoc directive 27679 * @name ngBlur 27680 * 27681 * @description 27682 * Specify custom behavior on blur event. 27683 * 27684 * A [blur event](https://developer.mozilla.org/en-US/docs/Web/Events/blur) fires when 27685 * an element has lost focus. 27686 * 27687 * Note: As the `blur` event is executed synchronously also during DOM manipulations 27688 * (e.g. removing a focussed input), 27689 * AngularJS executes the expression using `scope.$evalAsync` if the event is fired 27690 * during an `$apply` to ensure a consistent state. 27691 * 27692 * @element window, input, select, textarea, a 27693 * @priority 0 27694 * @param {expression} ngBlur {@link guide/expression Expression} to evaluate upon 27695 * blur. ({@link guide/expression#-event- Event object is available as `$event`}) 27696 * 27697 * @example 27698 * See {@link ng.directive:ngClick ngClick} 27699 */ 27700 27701/** 27702 * @ngdoc directive 27703 * @name ngCopy 27704 * 27705 * @description 27706 * Specify custom behavior on copy event. 27707 * 27708 * @element window, input, select, textarea, a 27709 * @priority 0 27710 * @param {expression} ngCopy {@link guide/expression Expression} to evaluate upon 27711 * copy. ({@link guide/expression#-event- Event object is available as `$event`}) 27712 * 27713 * @example 27714 <example name="ng-copy"> 27715 <file name="index.html"> 27716 <input ng-copy="copied=true" ng-init="copied=false; value='copy me'" ng-model="value"> 27717 copied: {{copied}} 27718 </file> 27719 </example> 27720 */ 27721 27722/** 27723 * @ngdoc directive 27724 * @name ngCut 27725 * 27726 * @description 27727 * Specify custom behavior on cut event. 27728 * 27729 * @element window, input, select, textarea, a 27730 * @priority 0 27731 * @param {expression} ngCut {@link guide/expression Expression} to evaluate upon 27732 * cut. ({@link guide/expression#-event- Event object is available as `$event`}) 27733 * 27734 * @example 27735 <example name="ng-cut"> 27736 <file name="index.html"> 27737 <input ng-cut="cut=true" ng-init="cut=false; value='cut me'" ng-model="value"> 27738 cut: {{cut}} 27739 </file> 27740 </example> 27741 */ 27742 27743/** 27744 * @ngdoc directive 27745 * @name ngPaste 27746 * 27747 * @description 27748 * Specify custom behavior on paste event. 27749 * 27750 * @element window, input, select, textarea, a 27751 * @priority 0 27752 * @param {expression} ngPaste {@link guide/expression Expression} to evaluate upon 27753 * paste. ({@link guide/expression#-event- Event object is available as `$event`}) 27754 * 27755 * @example 27756 <example name="ng-paste"> 27757 <file name="index.html"> 27758 <input ng-paste="paste=true" ng-init="paste=false" placeholder='paste here'> 27759 pasted: {{paste}} 27760 </file> 27761 </example> 27762 */ 27763 27764/** 27765 * @ngdoc directive 27766 * @name ngIf 27767 * @restrict A 27768 * @multiElement 27769 * 27770 * @description 27771 * The `ngIf` directive removes or recreates a portion of the DOM tree based on an 27772 * {expression}. If the expression assigned to `ngIf` evaluates to a false 27773 * value then the element is removed from the DOM, otherwise a clone of the 27774 * element is reinserted into the DOM. 27775 * 27776 * `ngIf` differs from `ngShow` and `ngHide` in that `ngIf` completely removes and recreates the 27777 * element in the DOM rather than changing its visibility via the `display` css property. A common 27778 * case when this difference is significant is when using css selectors that rely on an element's 27779 * position within the DOM, such as the `:first-child` or `:last-child` pseudo-classe
27779s. 27780 * 27781 * Note that when an element is removed using `ngIf` its scope is destroyed and a new scope 27782 * is created when the element is restored. The scope created within `ngIf` inherits from 27783 * its parent scope using 27784 * [prototypal inheritance](https://github.com/angular/angular.js/wiki/Understanding-Scopes#javascript-prototypal-inheritance). 27785 * An important implication of this is if `ngModel` is used within `ngIf` to bind to 27786 * a javascript primitive defined in the parent scope. In this case any modifications made to the 27787 * variable within the child scope will override (hide) the value in the parent scope. 27788 * 27789 * Also, `ngIf` recreates elements using their compiled state. An example of this behavior 27790 * is if an element's class attribute is directly modified after it's compiled, using something like 27791 * jQuery's `.addClass()` method, and the element is later removed. When `ngIf` recreates the element 27792 * the added class will be lost because the original compiled state is used to regenerate the element. 27793 * 27794 * Additionally, you can provide animations via the `ngAnimate` module to animate the `enter` 27795 * and `leave` effects. 27796 * 27797 * @animations 27798 * | Animation | Occurs | 27799 * |----------------------------------|-------------------------------------| 27800 * | {@link ng.$animate#enter enter} | just after the `ngIf` contents change and a new DOM element is created and injected into the `ngIf` container | 27801 * | {@link ng.$animate#leave leave} | just before the `ngIf` contents are removed from the DOM | 27802 * 27803 * @element ANY 27804 * @scope 27805 * @priority 600 27806 * @param {expression} ngIf If the {@link guide/expression expression} is falsy then 27807 * the element is removed from the DOM tree. If it is truthy a copy of the compiled 27808 * element is added to the DOM tree. 27809 * 27810 * @example 27811 <example module="ngAnimate" deps="angular-animate.js" animations="true" name="ng-if"> 27812 <file name="index.html"> 27813 <label>Click me: <input type="checkbox" ng-model="checked" ng-init="checked=true" /></label><br/> 27814 Show when checked: 27815 <span ng-if="checked" class="animate-if"> 27816 This is removed when the checkbox is unchecked. 27817 </span> 27818 </file> 27819 <file name="animations.css"> 27820 .animate-if { 27821 background:white; 27822 border:1px solid black; 27823 padding:10px; 27824 } 27825 27826 .animate-if.ng-enter, .animate-if.ng-leave { 27827 transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s; 27828 } 27829 27830 .animate-if.ng-enter, 27831 .animate-if.ng-leave.ng-leave-active { 27832 opacity:0; 27833 } 27834 27835 .animate-if.ng-leave, 27836 .animate-if.ng-enter.ng-enter-active { 27837 opacity:1; 27838 } 27839 </file> 27840 </example> 27841 */ 27842var ngIfDirective = ['$animate', '$compile', function($animate, $compile) { 27843 return { 27844 multiElement: true, 27845 transclude: 'element', 27846 priority: 600, 27847 terminal: true, 27848 restrict: 'A', 27849 $$tlb: true, 27850 link: function($scope, $element, $attr, ctrl, $transclude) { 27851 var block, childScope, previousElements; 27852 $scope.$watch($attr.ngIf, function ngIfWatchAction(value) { 27853 27854 if (value) { 27855 if (!childScope) { 27856 $transclude(function(clone, newScope) { 27857 childScope = newScope; 27858 clone[clone.length++] = $compile.$$createComment('end ngIf', $attr.ngIf); 27859 // Note: We only need the first/last node of the cloned nodes. 27860 // However, we need to keep the reference to the jqlite wrapper as it might be changed later 27861 // by a directive with templateUrl when its template arrives. 27862 block = { 27863 clone: clone 27864 }; 27865 $animate.enter(clone, $element.parent(), $element); 27866 }); 27867 } 27868 } else { 27869 if (previousElements) { 27870 previousElements.remove(); 27871 previousElements = null; 27872 } 27873 if (childScope) { 27874 childScope.$destroy(); 27875 childScope = null; 27876 } 27877 if (block) { 27878 previousElements = getBlockNodes(block.clone); 27879 $animate.leave(previousElements).done(function(response) { 27880 if (response !== false) previousElements = null; 27881 }); 27882 block = null; 27883 } 27884 } 27885 }); 27886 } 27887 }; 27888}]; 27889 27890/** 27891 * @ngdoc directive 27892 * @name ngInclude 27893 * @restrict ECA 27894 * 27895 * @description 27896 * Fetches, compiles and includes an external HTML fragment. 27897 * 27898 * By default, the template URL is restricted to the same domain and protocol as the 27899 * application document. This is done by calling {@link $sce#getTrustedResourceUrl 27900 * $sce.getTrustedResourceUrl} on it. To load templates from other domains or protocols 27901 * you may either {@link ng.$sceDelegateProvider#resourceUrlWhitelist whitelist them} or 27902 * {@link $sce#trustAsResourceUrl wrap them} as trusted values. Refer to Angular's {@link 27903 * ng.$sce Strict Contextual Escaping}. 27904 * 27905 * In addition, the browser's 27906 * [Same Origin Policy](https://code.google.com/p/browsersec/wiki/Part2#Same-origin_policy_for_XMLHttpRequest) 27907 * and [Cross-Origin Resource Sharing (CORS)](http://www.w3.org/TR/cors/) 27908 * policy may further restrict whether the template is successfully loaded. 27909 * For example, `ngInclude` won't work for cross-domain requests on all browsers and for `file://` 27910 * access on some browsers. 27911 * 27912 * @animations 27913 * | Animation | Occurs | 27914 * |----------------------------------|-------------------------------------| 27915 * | {@link ng.$animate#enter enter} | when the expression changes, on the new include | 27916 * | {@link ng.$animate#leave leave} | when the expression changes, on the old include | 27917 * 27918 * The enter and leave animation occur concurrently. 27919 * 27920 * @scope 27921 * @priority 400 27922 * 27923 * @param {string} ngInclude|src angular
vendor: 9,710 bytes, lines 27923-28200
27923 expression evaluating to URL. If the source is a string constant, 27924 * make sure you wrap it in **single** quotes, e.g. `src="'myPartialTemplate.html'"`. 27925 * @param {string=} onload Expression to evaluate when a new partial is loaded. 27926 * <div class="alert alert-warning"> 27927 * **Note:** When using onload on SVG elements in IE11, the browser will try to call 27928 * a function with the name on the window element, which will usually throw a 27929 * "function is undefined" error. To fix this, you can instead use `data-onload` or a 27930 * different form that {@link guide/directive#normalization matches} `onload`. 27931 * </div> 27932 * 27933 * @param {string=} autoscroll Whether `ngInclude` should call {@link ng.$anchorScroll 27934 * $anchorScroll} to scroll the viewport after the content is loaded. 27935 * 27936 * - If the attribute is not set, disable scrolling. 27937 * - If the attribute is set without value, enable scrolling. 27938 * - Otherwise enable scrolling only if the expression evaluates to truthy value. 27939 * 27940 * @example 27941 <example module="includeExample" deps="angular-animate.js" animations="true" name="ng-include"> 27942 <file name="index.html"> 27943 <div ng-controller="ExampleController"> 27944 <select ng-model="template" ng-options="t.name for t in templates"> 27945 <option value="">(blank)</option> 27946 </select> 27947 url of the template: <code>{{template.url}}</code> 27948 <hr/> 27949 <div class="slide-animate-container"> 27950 <div class="slide-animate" ng-include="template.url"></div> 27951 </div> 27952 </div> 27953 </file> 27954 <file name="script.js"> 27955 angular.module('includeExample', ['ngAnimate']) 27956 .controller('ExampleController', ['$scope', function($scope) { 27957 $scope.templates = 27958 [{ name: 'template1.html', url: 'template1.html'}, 27959 { name: 'template2.html', url: 'template2.html'}]; 27960 $scope.template = $scope.templates[0]; 27961 }]); 27962 </file> 27963 <file name="template1.html"> 27964 Content of template1.html 27965 </file> 27966 <file name="template2.html"> 27967 Content of template2.html 27968 </file> 27969 <file name="animations.css"> 27970 .slide-animate-container { 27971 position:relative; 27972 background:white; 27973 border:1px solid black; 27974 height:40px; 27975 overflow:hidden; 27976 } 27977 27978 .slide-animate { 27979 padding:10px; 27980 } 27981 27982 .slide-animate.ng-enter, .slide-animate.ng-leave { 27983 transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s; 27984 27985 position:absolute; 27986 top:0; 27987 left:0; 27988 right:0; 27989 bottom:0; 27990 display:block; 27991 padding:10px; 27992 } 27993 27994 .slide-animate.ng-enter { 27995 top:-50px; 27996 } 27997 .slide-animate.ng-enter.ng-enter-active { 27998 top:0; 27999 } 28000 28001 .slide-animate.ng-leave { 28002 top:0; 28003 } 28004 .slide-animate.ng-leave.ng-leave-active { 28005 top:50px; 28006 } 28007 </file> 28008 <file name="protractor.js" type="protractor"> 28009 var templateSelect = element(by.model('template')); 28010 var includeElem = element(by.css('[ng-include]')); 28011 28012 it('should load template1.html', function() { 28013 expect(includeElem.getText()).toMatch(/Content of template1.html/); 28014 }); 28015 28016 it('should load template2.html', function() { 28017 if (browser.params.browser === 'firefox') { 28018 // Firefox can't handle using selects 28019 // See https://github.com/angular/protractor/issues/480 28020 return; 28021 } 28022 templateSelect.click(); 28023 templateSelect.all(by.css('option')).get(2).click(); 28024 expect(includeElem.getText()).toMatch(/Content of template2.html/); 28025 }); 28026 28027 it('should change to blank', function() { 28028 if (browser.params.browser === 'firefox') { 28029 // Firefox can't handle using selects 28030 return; 28031 } 28032 templateSelect.click(); 28033 templateSelect.all(by.css('option')).get(0).click(); 28034 expect(includeElem.isPresent()).toBe(false); 28035 }); 28036 </file> 28037 </example> 28038 */ 28039 28040 28041/** 28042 * @ngdoc event 28043 * @name ngInclude#$includeContentRequested 28044 * @eventType emit on the scope ngInclude was declared in 28045 * @description 28046 * Emitted every time the ngInclude content is requested. 28047 * 28048 * @param {Object} angularEvent Synthetic event object. 28049 * @param {String} src URL of content to load. 28050 */ 28051 28052 28053/** 28054 * @ngdoc event 28055 * @name ngInclude#$includeContentLoaded 28056 * @eventType emit on the current ngInclude scope 28057 * @description 28058 * Emitted every time the ngInclude content is reloaded. 28059 * 28060 * @param {Object} angularEvent Synthetic event object. 28061 * @param {String} src URL of content to load. 28062 */ 28063 28064 28065/** 28066 * @ngdoc event 28067 * @name ngInclude#$includeContentError 28068 * @eventType emit on the scope ngInclude was declared in 28069 * @description 28070 * Emitted when a template HTTP request yields an erroneous response (status < 200 || status > 299) 28071 * 28072 * @param {Object} angularEvent Synthetic event object. 28073 * @param {String} src URL of content to load. 28074 */ 28075var ngIncludeDirective = ['$templateRequest', '$anchorScroll', '$animate', 28076 function($templateRequest, $anchorScroll, $animate) { 28077 return { 28078 restrict: 'ECA', 28079 priority: 400, 28080 terminal: true, 28081 transclude: 'element', 28082 controller: angular.noop, 28083 compile: function(element, attr) { 28084 var srcExp = attr.ngInclude || attr.src, 28085 onloadExp = attr.onload || '', 28086 autoScrollExp = attr.autoscroll; 28087 28088 return function(scope, $element, $attr, ctrl, $transclude) { 28089 var changeCounter = 0, 28090 currentScope, 28091 previousElement, 28092 currentElement; 28093 28094 var cleanupLastIncludeContent = function() { 28095 if (previousElement) { 28096 previousElement.remove(); 28097 previousElement = null; 28098 } 28099 if (currentScope) { 28100 currentScope.$destroy(); 28101 currentScope = null; 28102 } 28103 if (currentElement) { 28104 $animate.leave(currentElement).done(function(response) { 28105 if (response !== false) previousElement = null; 28106 }); 28107 previousElement = currentElement; 28108 currentElement = null; 28109 } 28110 }; 28111 28112 scope.$watch(srcExp, function ngIncludeWatchAction(src) { 28113 var afterAnimation = function(response) { 28114 if (response !== false && isDefined(autoScrollExp) && 28115 (!autoScrollExp || scope.$eval(autoScrollExp))) { 28116 $anchorScroll(); 28117 } 28118 }; 28119 var thisChangeId = ++changeCounter; 28120 28121 if (src) { 28122 //set the 2nd param to true to ignore the template request error so that the inner 28123 //contents and scope can be cleaned up. 28124 $templateRequest(src, true).then(function(response) { 28125 if (scope.$$destroyed) return; 28126 28127 if (thisChangeId !== changeCounter) return; 28128 var newScope = scope.$new(); 28129 ctrl.template = response; 28130 28131 // Note: This will also link all children of ng-include that were contained in the original 28132 // html. If that content contains controllers, ... they could pollute/change the scope. 28133 // However, using ng-include on an element with additional content does not make sense... 28134 // Note: We can't remove them in the cloneAttchFn of $transclude as that 28135 // function is called before linking the content, which would apply child 28136 // directives to non existing elements. 28137 var clone = $transclude(newScope, function(clone) { 28138 cleanupLastIncludeContent(); 28139 $animate.enter(clone, null, $element).done(afterAnimation); 28140 }); 28141 28142 currentScope = newScope; 28143 currentElement = clone; 28144 28145 currentScope.$emit('$includeContentLoaded', src); 28146 scope.$eval(onloadExp); 28147 }, function() { 28148 if (scope.$$destroyed) return; 28149 28150 if (thisChangeId === changeCounter) { 28151 cleanupLastIncludeContent(); 28152 scope.$emit('$includeContentError', src); 28153 } 28154 }); 28155 scope.$emit('$includeContentRequested', src); 28156 } else { 28157 cleanupLastIncludeContent(); 28158 ctrl.template = null; 28159 } 28160 }); 28161 }; 28162 } 28163 }; 28164}]; 28165 28166// This directive is called during the $transclude call of the first `ngInclude` directive. 28167// It will replace and compile the content of the element with the loaded template. 28168// We need this directive so that the element content is already filled when 28169// the link function of another directive on the same element as ngInclude 28170// is called. 28171var ngIncludeFillContentDirective = ['$compile', 28172 function($compile) { 28173 return { 28174 restrict: 'ECA', 28175 priority: -400, 28176 require: 'ngInclude', 28177 link: function(scope, $element, $attr, ctrl) { 28178 if (toString.call($element[0]).match(/SVG/)) { 28179 // WebKit: https://bugs.webkit.org/show_bug.cgi?id=135698 --- SVG elements do not 28180 // support innerHTML, so detect this here and try to generate the contents 28181 // specially. 28182 $element.empty(); 28183 $compile(jqLiteBuildFragment(ctrl.template, window.document).childNodes)(scope, 28184 function namespaceAdaptedClone(clone) { 28185 $element.append(clone); 28186 }, {futureParentElement: $element}); 28187 return; 28188 } 28189 28190 $element.html(ctrl.template); 28191 $compile($element.contents())(scope); 28192 } 28193 }; 28194 }]; 28195 28196/** 28197 * @ngdoc directive 28198 * @name ngInit 28199 * @restrict AC 28200 *
28200 28201 * @description 28202 * The `ngInit` directive allows you to evaluate an expression in the 28203 * current scope. 28204 * 28205 * <div class="alert alert-danger"> 28206 * This directive can be abused to add unnecessary amounts of logic into your templates. 28207 * There are only a few appropriate uses of `ngInit`, such as for aliasing special properties of 28208 * {@link ng.directive:ngRepeat `ngRepeat`}, as seen in the demo below; and for injecting data via 28209 * server side scripting. Besides these few cases, you should use {@link guide/controller controllers} 28210 * rather than `ngInit` to initialize values on a scope. 28211 * </div> 28212 * 28213 * <div class="alert alert-warning"> 28214 * **Note**: If you have assignment in `ngInit` along with a {@link ng.$filter `filter`}, make 28215 * sure you have parentheses to ensure correct operator precedence: 28216 * <pre class="prettyprint"> 28217 * `<div ng-init="test1 = ($index | toString)"></div>` 28218 * </pre> 28219 * </div> 28220 * 28221 * @priority 450 28222 * 28223 * @element ANY 28224 * @param {expression} ngInit {@link guide/expression Expression} to eval. 28225 * 28226 * @example 28227 <example module="initExample" name="ng-init"> 28228 <file name="index.html"> 28229 <script> 28230 angular.module('initExample', []) 28231 .controller('ExampleController', ['$scope', function($scope) { 28232 $scope.list = [['a', 'b'], ['c', 'd']]; 28233 }]); 28234 </script>
28235 <div ng-controller="ExampleController"> 28236 <div ng-repeat="innerList in list" ng-init="outerIndex = $index"> 28237 <div ng-repeat="value in innerList" ng-init="innerIndex = $index"> 28238 <span class="example-init">list[ {{outerIndex}} ][ {{innerIndex}} ] = {{value}};</span> 28239 </div> 28240 </div> 28241 </div> 28242 </file> 28243 <file name="protractor.js" type="protractor"> 28244 it('should alias index positions', function() { 28245 var elements = element.all(by.css('.example-init')); 28246 expect(elements.get(0).getText()).toBe('list[ 0 ][ 0 ] = a;'); 28247 expect(elements.get(1).getText()).toBe('list[ 0 ][ 1 ] = b;'); 28248 expect(elements.get(2).getText()).toBe('list[ 1 ][ 0 ] = c;'); 28249 expect(elements.get(3).getText()).toBe('list[ 1 ][ 1 ] = d;'); 28250 }); 28251 </file> 28252 </example> 28253 */ 28254var ngInitDirective = ngDirective({ 28255 priority: 450, 28256 compile: function() { 28257 return { 28258 pre: function(scope, element, attrs) { 28259 scope.$eval(attrs.ngInit); 28260 } 28261 }; 28262 } 28263}); 28264 28265/** 28266 * @ngdoc directive 28267 * @name ngList 28268 * 28269 * @description 28270 * Text input that converts between a delimited string and an array of strings. The default 28271 * delimiter is a comma followed by a space - equivalent to `ng-list=", "`. You can specify a custom 28272 * delimiter as the value of the `ngList` attribute - for example, `ng-list=" | "`. 28273 * 28274 * The behaviour of the directive is affected by the use of the `ngTrim` attribute. 28275 * * If `ngTrim` is set to `"false"` then whitespace around both the separator and each 28276 * list item is respected. This implies that the user of the directive is responsible for 28277 * dealing with whitespace but also allows you to use whitespace as a delimiter, such as a 28278 * tab or newline character. 28279 * * Otherwise whitespace around the delimiter is ignored when splitting (although it is respected 28280 * when joining the list items back together) and whitespace around each list item is stripped 28281 * before it is added to the model. 28282 * 28283 * ### Example with Validation 28284 * 28285 * <example name="ngList-directive" module="listExample"> 28286 * <file name="app.js"> 28287 * angular.module('listExample', []) 28288 * .controller('ExampleController', ['$scope', function($scope) { 28289 * $scope.names = ['morpheus', 'neo', 'trinity']; 28290 * }]); 28291 * </file> 28292 * <file name="index.html">
28293 * <form name="myForm" ng-controller="ExampleController"> 28294 * <label>List: <input name="namesInput" ng-model="names" ng-list required></label> 28295 * <span role="alert"> 28296 * <span class="error" ng-show="myForm.namesInput.$error.required"> 28297 * Required!</span> 28298 * </span> 28299 * <br> 28300 * <tt>names = {{names}}</tt><br/> 28301 * <tt>myForm.namesInput.$valid = {{myForm.namesInput.$valid}}</tt><br/> 28302 * <tt>myForm.namesInput.$error = {{myForm.namesInput.$error}}</tt><br/> 28303 * <tt>myForm.$valid = {{myForm.$valid}}</tt><br/> 28304 * <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/> 28305 * </form> 28306 * </file> 28307 * <file name="protractor.js" type="protractor"> 28308 * var listInput = element(by.model('names')); 28309 * var names = element(by.exactBinding('names')); 28310 * var valid = element(by.binding('myForm.namesInput.$valid')); 28311 * var error = element(by.css('span.error')); 28312 * 28313 * it('should initialize to model', function() { 28314 * expect(names.getText()).toContain('["morpheus","neo","trinity"]'); 28315 * expect(valid.getText()).toContain('true'); 28316 * expect(error.getCssValue('display')).toBe('none'); 28317 * }); 28318 * 28319 * it('should be invalid if empty', function() { 28320 * listInput.clear(); 28321 * listInput.sendKeys(''); 28322 * 28323 * expect(names.getText()).toContain(''); 28324 * expect(valid.getText()).toContain('false'); 28325 * expect(error.getCssValue('display')).not.toBe('none'); 28326 * }); 28327 * </file> 28328 * </example> 28329 * 28330 * ### Example - splitting on newline 28331 * <example name="ngList-directive-newlines"> 28332 * <file name="index.html"> 28333 * <textarea ng-model="list" ng-list=" " ng-trim="false"></textarea> 28334 * <pre>{{ list | json }}</pre> 28335 * </file> 28336 * <file name="protractor.js" type="protractor"> 28337 * it("should split the text by newlines", function() { 28338 * var listInput = element(by.model('list')); 28339 * var output = element(by.binding('list | json')); 28340 * listInput.sendKeys('abc\ndef\nghi'); 28341 * expect(output.getText()).toContain('[\n "abc",\n "def",\n "ghi"\n]'); 28342 * }); 28343 * </file> 28344 * </example> 28345 * 28346 * @element input 28347 * @param {string=} ngList optional delimiter that should be used to split the value. 28348 */ 28349var ngListDirective = function() { 28350 return { 28351 restrict: 'A', 28352 priority: 100, 28353 require: 'ngModel', 28354 link: function(scope, element, attr, ctrl) { 28355 var ngList = attr.ngList || ', '; 28356 var trimValues = attr.ngTrim !== 'false'; 28357 var separator = trimValues ? trim(ngList) : ngList; 28358 28359 var parse = function(viewValue) { 28360 // If the viewValue is invalid (say required but empty) it will be `undefined` 28361 if (isUndefined(viewValue)) return; 28362 28363 var list = []; 28364 28365 if (viewValue) { 28366 forEach(viewValue.split(separator), function(value) { 28367 if (value) list.push(trimValues ? trim(value) : value); 28368 }); 28369 } 28370 28371 return list; 28372 }; 28373 28374 ctrl.$parsers.push(parse); 28375 ctrl.$formatters.push(function(value) { 28376 if (isArray(value)) { 28377 return value.join(ngList); 28378 } 28379 28380 return undefined; 28381 }); 28382 28383 // Override the standard $isEmpty because an empty array means the input is empty. 28384 ctrl.$isEmpty = function(value) { 28385 return !value || !value.length; 28386 }; 28387 } 28388 }; 28389}; 28390 28391/* global VALID_CLASS: true, 28392 INVALID_CLASS: true, 28393 PRISTINE_CLASS: true, 28394 DIRTY_CLASS: true, 28395 UNTOUCHED_CLASS: true, 28396 TOUCHED_CLASS: true, 28397 PENDING_CLASS: true, 28398 addSetValidityMethod: true, 28399 setupValidity: true, 28400 defaultModelOptions: false 28401*/ 28402 28403 28404var VALID_CLASS = 'ng-valid', 28405 INVALID_CLASS = 'ng-invalid', 28406 PRISTINE_CLASS = 'ng-pristine', 28407 DIRTY_CLASS = 'ng-dirty', 28408 UNTOUCHED_CLASS = 'ng-untouched', 28409 TOUCHED_CLASS = 'ng-touched', 28410 EMPTY_CLASS = 'ng-empty', 28411 NOT_EMPTY_CLASS = 'ng-not-empty'; 28412 28413var ngModelMinErr = minErr('ngModel'); 28414 28415/** 28416 * @ngdoc type 28417 * @name ngModel.NgModelController 28418 * 28419 * @property {*} $viewValue The actual value from the control's view. For `input` elements, this is a 28420 * String. See {@link ngModel.NgModelController#$setViewValue} for information about when the $viewValue 28421 * is set. 28422 * 28423 * @property {*} $modelValue The value in the model that the control is bound to. 28424 * 28425 * @property {Array.<Function>} $parsers Array of functions to execute, as a pipeline, whenever 28426 * the control updates the ngModelController with a new {@link ngModel.NgModelController#$viewValue 28427 `$viewValue`} from the DOM, usually via user input. 28428 See {@link ngModel.NgModelController#$setViewValue `$setViewValue()`} for a detailed lifecycle explanation. 28429 Note that the `$parsers` are not called when the bound ngModel expression changes programmatically. 28430 28431 The functions are called in array order, each passing 28432 its return value through to the next. The last return value is forwarded to the 28433 {@link ngModel.NgModelController#$validators `$validators`} collection. 28434 28435 Parsers are used to sanitize / convert the {@link ngModel.NgModelController#$viewValue 28436 `$viewValue`}. 28437 28438 Returning `undefined` from a parser means a parse error occurred. In that case, 28439 no {@link ngModel.NgModelController#$validators `$validators`} will run and the `ngModel` 28440 will be set to `undefined` unless {@link ngModelOptions `ngModelOptions.allowInvalid`} 28441 is set to `true`. The parse error is stored in `ngModel.$error.parse`. 28442 28443 This simple example shows a parser that would convert text input value to lowercase: 28444 * ```js 28445 * function parse(value) { 28446 * if (value) { 28447 * return value.toLowerCase(); 28448 * } 28449 * } 28450 * ngModelController.$parsers.push(parse); 28451 * ``` 28452 28453 * 28454 * @property {Array.<Function>} $formatters Array of functions to execute, as a pipeline, whenever 28455 the bound ngModel expression changes programmatically. The `$formatters` are not called when the 28456 value of the control is changed by user interaction. 28457 28458 Formatters are used to format / convert the {@link ngModel.NgModelController#$modelValue 28459 `$modelValue`} for display in the control. 28460 28461 The functions are called in reverse array order, each passing the value through to the 28462 next. The last return value is used as the actual DOM value. 28463 28464 This simple example shows a formatter that would convert the model value to uppercase: 28465 28466 * ```js 28467 * function format(value) { 28468 * if (value) { 28469 * return value.toUpperCase(); 28470 * } 28471 * } 28472 * ngModel.$formatters.push(format); 28473 * ``` 28474 * 28475 * @property {Object.<string, function>} $validators A collection of validators that are applied 28476 * whenever the model value changes. The key value within the object refers to the name of the 28477 * validator while the function refers to the validation operation. The validation operation is 28478 * provided with the model value as an argument and must return a true or false value depending 28479 * on the response of that validation. 28480 * 28481 * ```js 28482 * ngModel.$validators.validCharacters = function(modelValue, viewValue) { 28483 * var value = modelValue || viewValue; 28484 * return /[0-9]+/.test(value) && 28485 * /[a-z]+/.test(value) && 28486 * /[A-Z]+/.test(value) && 28487 * /\W+/.test(value); 28488 * }; 28489 * ``` 28490 * 28491 * @property {Object.<string, function>} $asyncValidators A collection of validations that are expected to 28492 * perform an asynchronous validation (e.g. a HTTP request). The validation function that is provided 28493 * is expected to return a promise when it is run during the model validation process. Once the promise 28494 * is delivered then the validation status will be set to true when fulfilled and false when rejected. 28495 * When the asynchronous validators are triggered, each of the validators will run in parallel and the model 28496 * value will only be updated once all validators have been fulfilled. As long as an asynchronous validator 28497 * is unfulfilled, its key will be added to the controllers `$pending` property. Also, all asynchronous validators 28498 * will only run once all synchronous validators have passed. 28499 * 28500 * Please note that if $http is used then it is important that the server returns a success HTTP response code 28501 * in order to fulfill the validation and a status level of `4xx` in order to reject the validation. 28502 * 28503 * ```js 28504 * ngModel.$asyncValidators.uniqueUsername = function(modelValue, viewValue) { 28505 * var value = modelValue || viewValue; 28506 * 28507 * // Lookup user by username 28508 * return $http.get('/api/users/' + value). 28509 * then(function resolved() { 28510 * //username exists, this means validation fails 28511 * return $q.reject('exists'); 28512 * }, function rejected() { 28513 * //username does not exist, therefore this validation passes 28514 * return true; 28515 * }); 28516 * }; 28517 * ``` 28518 * 28519 * @property {Array.<Function>} $viewChangeListeners Array of functions to execute whenever the 28520 * view value has changed. It is called with no arguments, and its return value is ignored. 28521 * This can be used in place of additional $watches against the model value. 28522 * 28523 * @property {Object} $error An object hash with all failing validator ids as keys. 28524 * @property {Object} $pending An object hash with all pending validator ids as keys. 28525 * 28526 * @property {boolean} $untouched True if control has not lost focus yet. 28527 * @property {boolean} $touched True if control has lost focus. 28528 * @property {boolean} $pristine True if user has not interacted with the control yet. 28529 * @property {boolean} $dirty True if user has already interacted with the control. 28530 * @property {boolean} $valid True if there is no error. 28531 * @property {boolean}
28531 $invalid True if at least one error on the control. 28532 * @property {string} $name The name attribute of the control. 28533 * 28534 * @description 28535 * 28536 * `NgModelController` provides API for the {@link ngModel `ngModel`} directive. 28537 * The controller contains services for data-binding, validation, CSS updates, and value formatting 28538 * and parsing. It purposefully does not contain any logic which deals with DOM rendering or 28539 * listening to DOM events. 28540 * Such DOM related logic should be provided by other directives which make use of 28541 * `NgModelController` for data-binding to control elements. 28542 * Angular provides this DOM logic for most {@link input `input`} elements. 28543 * At the end of this page you can find a {@link ngModel.NgModelController#custom-control-example 28544 * custom control example} that uses `ngModelController` to bind to `contenteditable` elements. 28545 * 28546 * @example 28547 * ### Custom Control Example 28548 * This example shows how to use `NgModelController` with a custom control to achieve 28549 * data-binding. Notice how different directives (`contenteditable`, `ng-model`, and `required`) 28550 * collaborate together to achieve the desired result. 28551 * 28552 * `contenteditable` is an HTML5 attribute, which tells the browser to let the element 28553 * contents be edited in place by the user. 28554 * 28555 * We are using the {@link ng.service:$sce $sce} service here and include the {@link ngSanitize $sanitize} 28556 * module to automatically remove "bad" content like inline event listener (e.g. `<span onclick="...">`). 28557 * However, as we are using `$sce` the model can still decide to provide unsafe content if it marks 28558 * that content using the `$sce` service. 28559 * 28560 * <example name="NgModelController" module="customControl" deps="angular-sanitize.js"> 28561 <file name="style.css"> 28562 [contenteditable] { 28563 border: 1px solid black; 28564 background-color: white; 28565 min-height: 20px; 28566 } 28567 28568 .ng-invalid { 28569 border: 1px solid red; 28570 } 28571 28572 </file> 28573 <file name="script.js"> 28574 angular.module('customControl', ['ngSanitize']). 28575 directive('contenteditable', ['$sce', function($sce) { 28576 return { 28577 restrict: 'A', // only activate on element attribute 28578 require: '?ngModel', // get a hold of NgModelController 28579 link: function(scope, element, attrs, ngModel) { 28580 if (!ngModel) return; // do nothing if no ng-model 28581 28582 // Specify how UI should be updated 28583 ngModel.$render = function() { 28584 element.html($sce.getTrustedHtml(ngModel.$viewValue || '')); 28585 }; 28586 28587 // Listen for change events to enable binding 28588 element.on('blur keyup change', function() { 28589 scope.$evalAsync(read); 28590 }); 28591 read(); // initialize 28592 28593 // Write data to the model 28594 function read() { 28595 var html = element.html(); 28596 // When we clear the content editable the browser leaves a <br> behind 28597 // If strip-br attribute is provided then we strip this out 28598 if (attrs.stripBr && html === '<br>') { 28599 html = ''; 28600 } 28601 ngModel.$setViewValue(html); 28602 } 28603 } 28604 }; 28605 }]); 28606 </file> 28607 <file name="index.html"> 28608 <form name="myForm"> 28609 <div contenteditable 28610 name="myWidget" ng-model="userContent" 28611 strip-br="true" 28612 required>Change me!</div> 28613 <span ng-show="myForm.myWidget.$error.required">Required!</span> 28614 <hr> 28615 <textarea ng-model="userContent" aria-label="Dynamic textarea"></textarea> 28616 </form> 28617 </file> 28618 <file name="protractor.js" type="protractor"> 28619 it('should data-bind and become invalid', function() { 28620 if (browser.params.browser === 'safari' || browser.params.browser === 'firefox') { 28621 // SafariDriver can't handle contenteditable 28622 // and Firefox driver can't clear contenteditables very well 28623 return; 28624 } 28625 var contentEditable = element(by.css('[contenteditable]')); 28626 var content = 'Change me!'; 28627 28628 expect(contentEditable.getText()).toEqual(content); 28629 28630 contentEditable.clear(); 28631 contentEditable.sendKeys(protractor.Key.BACK_SPACE); 28632 expect(contentEditable.getText()).toEqual(''); 28633 expect(contentEditable.getAttribute('class')).toMatch(/ng-invalid-required/); 28634 }); 28635 </file> 28636 * </example> 28637 * 28638 * 28639 */ 28640NgModelController.$inject = ['$scope', '$exceptionHandler', '$attrs', '$element', '$parse', '$animate', '$timeout', '$q', '$interpolate']; 28641function NgModelController($scope, $exceptionHandler, $attr, $element, $parse, $animate, $timeout, $q, $interpolate) { 28642 this.$viewValue = Number.NaN; 28643 this.$modelValue = Number.NaN; 28644 this.$$rawModelValue = undefined; // stores the parsed modelValue / model set from scope regardless of validity. 28645 this.$validators = {}; 28646 this.$asyncValidators = {}; 28647 this.$parsers = []; 28648 this.$formatters = []; 28649 this.$viewChangeListeners = []; 28650 this.$untouched = true; 28651 this.$touched = false;
vendor: 4,840 bytes, lines 28652-28781
28652 this.$pristine = true; 28653 this.$dirty = false; 28654 this.$valid = true; 28655 this.$invalid = false; 28656 this.$error = {}; // keep invalid keys here 28657 this.$$success = {}; // keep valid keys here 28658 this.$pending = undefined; // keep pending keys here 28659 this.$name = $interpolate($attr.name || '', false)($scope); 28660 this.$$parentForm = nullFormCtrl; 28661 this.$options = defaultModelOptions; 28662 28663 this.$$parsedNgModel = $parse($attr.ngModel); 28664 this.$$parsedNgModelAssign = this.$$parsedNgModel.assign; 28665 this.$$ngModelGet = this.$$parsedNgModel; 28666 this.$$ngModelSet = this.$$parsedNgModelAssign; 28667 this.$$pendingDebounce = null; 28668 this.$$parserValid = undefined; 28669 28670 this.$$currentValidationRunId = 0; 28671 28672 // https://github.com/angular/angular.js/issues/15833 28673 // Prevent `$$scope` from being iterated over by `copy` when NgModelController is deep watched 28674 Object.defineProperty(this, '$$scope', {value: $scope}); 28675 this.$$attr = $attr; 28676 this.$$element = $element; 28677 this.$$animate = $animate; 28678 this.$$timeout = $timeout; 28679 this.$$parse = $parse; 28680 this.$$q = $q; 28681 this.$$exceptionHandler = $exceptionHandler; 28682 28683 setupValidity(this); 28684 setupModelWatcher(this); 28685} 28686 28687NgModelController.prototype = { 28688 $$initGetterSetters: function() { 28689 if (this.$options.getOption('getterSetter')) { 28690 var invokeModelGetter = this.$$parse(this.$$attr.ngModel + '()'), 28691 invokeModelSetter = this.$$parse(this.$$attr.ngModel + '($$$p)'); 28692 28693 this.$$ngModelGet = function($scope) { 28694 var modelValue = this.$$parsedNgModel($scope); 28695 if (isFunction(modelValue)) { 28696 modelValue = invokeModelGetter($scope); 28697 } 28698 return modelValue; 28699 }; 28700 this.$$ngModelSet = function($scope, newValue) { 28701 if (isFunction(this.$$parsedNgModel($scope))) { 28702 invokeModelSetter($scope, {$$$p: newValue}); 28703 } else { 28704 this.$$parsedNgModelAssign($scope, newValue); 28705 } 28706 }; 28707 } else if (!this.$$parsedNgModel.assign) { 28708 throw ngModelMinErr('nonassign', 'Expression \'{0}\' is non-assignable. Element: {1}', 28709 this.$$attr.ngModel, startingTag(this.$$element)); 28710 } 28711 }, 28712 28713 28714 /** 28715 * @ngdoc method 28716 * @name ngModel.NgModelController#$render 28717 * 28718 * @description 28719 * Called when the view needs to be updated. It is expected that the user of the ng-model 28720 * directive will implement this method. 28721 * 28722 * The `$render()` method is invoked in the following situations: 28723 * 28724 * * `$rollbackViewValue()` is called. If we are rolling back the view value to the last 28725 * committed value then `$render()` is called to update the input control. 28726 * * The value referenced by `ng-model` is changed programmatically and both the `$modelValue` and 28727 * the `$viewValue` are different from last time. 28728 * 28729 * Since `ng-model` does not do a deep watch, `$render()` is only invoked if the values of 28730 * `$modelValue` and `$viewValue` are actually different from their previous values. If `$modelValue` 28731 * or `$viewValue` are objects (rather than a string or number) then `$render()` will not be 28732 * invoked if you only change a property on the objects. 28733 */ 28734 $render: noop, 28735 28736 /** 28737 * @ngdoc method 28738 * @name ngModel.NgModelController#$isEmpty 28739 * 28740 * @description 28741 * This is called when we need to determine if the value of an input is empty. 28742 * 28743 * For instance, the required directive does this to work out if the input has data or not. 28744 * 28745 * The default `$isEmpty` function checks whether the value is `undefined`, `''`, `null` or `NaN`. 28746 * 28747 * You can override this for input directives whose concept of being empty is different from the 28748 * default. The `checkboxInputType` directive does this because in its case a value of `false` 28749 * implies empty. 28750 * 28751 * @param {*} value The value of the input to check for emptiness. 28752 * @returns {boolean} True if `value` is "empty". 28753 */ 28754 $isEmpty: function(value) { 28755 // eslint-disable-next-line no-self-compare 28756 return isUndefined(value) || value === '' || value === null || value !== value; 28757 }, 28758 28759 $$updateEmptyClasses: function(value) { 28760 if (this.$isEmpty(value)) { 28761 this.$$animate.removeClass(this.$$element, NOT_EMPTY_CLASS); 28762 this.$$animate.addClass(this.$$element, EMPTY_CLASS); 28763 } else { 28764 this.$$animate.removeClass(this.$$element, EMPTY_CLASS); 28765 this.$$animate.addClass(this.$$element, NOT_EMPTY_CLASS); 28766 } 28767 }, 28768 28769 /** 28770 * @ngdoc method 28771 * @name ngModel.NgModelController#$setPristine 28772 * 28773 * @description 28774 * Sets the control to its pristine state. 28775 * 28776 * This method can be called to remove the `ng-dirty` class and set the control to its pristine 28777 * state (`ng-pristine` class). A model is considered to be pristine when the control 28778 * has not been changed from when first compiled. 28779 */ 28780 $setPristine: function() { 28781 this.$dirty = false;
28782 this.$pristine = true; 28783 this.$$animate.removeClass(this.$$element, DIRTY_CLASS); 28784 this.$$animate.addClass(this.$$element, PRISTINE_CLASS); 28785 }, 28786 28787 /** 28788 * @ngdoc method 28789 * @name ngModel.NgModelController#$setDirty 28790 * 28791 * @description 28792 * Sets the control to its dirty state. 28793 * 28794 * This method can be called to remove the `ng-pristine` class and set the control to its dirty 28795 * state (`ng-dirty` class). A model is considered to be dirty when the control has been changed 28796 * from when first compiled. 28797 */ 28798 $setDirty: function() { 28799 this.$dirty = true; 28800 this.$pristine = false; 28801 this.$$animate.removeClass(this.$$element, PRISTINE_CLASS); 28802 this.$$animate.addClass(this.$$element, DIRTY_CLASS); 28803 this.$$parentForm.$setDirty(); 28804 }, 28805 28806 /** 28807 * @ngdoc method 28808 * @name ngModel.NgModelController#$setUntouched 28809 * 28810 * @description 28811 * Sets the control to its untouched state. 28812 * 28813 * This method can be called to remove the `ng-touched` class and set the control to its 28814 * untouched state (`ng-untouched` class). Upon compilation, a model is set as untouched 28815 * by default, however this function can be used to restore that state if the model has 28816 * already been touched by the user. 28817 */ 28818 $setUntouched: function() { 28819 this.$touched = false; 28820 this.$untouched = true; 28821 this.$$animate.setClass(this.$$element, UNTOUCHED_CLASS, TOUCHED_CLASS); 28822 }, 28823 28824 /** 28825 * @ngdoc method 28826 * @name ngModel.NgModelController#$setTouched 28827 * 28828 * @description 28829 * Sets the control to its touched state. 28830 * 28831 * This method can be called to remove the `ng-untouched` class and set the control to its 28832 * touched state (`ng-touched` class). A model is considered to be touched when the user has 28833 * first focused the control element and then shifted focus away from the control (blur event). 28834 */ 28835 $setTouched: function() { 28836 this.$touched = true; 28837 this.$untouched = false; 28838 this.$$animate.setClass(this.$$element, TOUCHED_CLASS, UNTOUCHED_CLASS); 28839 }, 28840 28841 /** 28842 * @ngdoc method 28843 * @name ngModel.NgModelController#$rollbackViewValue 28844 * 28845 * @description 28846 * Cancel an update and reset the input element's value to prevent an update to the `$modelValue`, 28847 * which may be caused by a pending debounced event or because the input is waiting for some 28848 * future event. 28849 * 28850 * If you have an input that uses `ng-model-options` to set up debounced updates or updates that 28851 * depend on special events such as `blur`, there can be a period when the `$viewValue` is out of 28852 * sync with the ngModel's `$modelValue`. 28853 * 28854 * In this case, you can use `$rollbackViewValue()` to manually cancel the debounced / future update 28855 * and reset the input to the last committed view value. 28856 * 28857 * It is also possible that you run into difficulties if you try to update the ngModel's `$modelValue` 28858 * programmatically before these debounced/future events have resolved/occurred, because Angular's 28859 * dirty checking mechanism is not able to tell whether the model has actually changed or not. 28860 * 28861 * The `$rollbackViewValue()` method should be called before programmatically changing the model of an 28862 * input which may have such events pending. This is important in order to make sure that the 28863 * input field will be updated with the new model value and any pending operations are cancelled. 28864 * 28865 * <example name="ng-model-cancel-update" module="cancel-update-example"> 28866 * <file name="app.js"> 28867 * angular.module('cancel-update-example', []) 28868 * 28869 * .controller('CancelUpdateController', ['$scope', function($scope) { 28870 * $scope.model = {value1: '', value2: ''}; 28871 * 28872 * $scope.setEmpty = function(e, value, rollback) { 28873 * if (e.keyCode === 27) { 28874 * e.preventDefault(); 28875 * if (rollback) { 28876 * $scope.myForm[value].$rollbackViewValue(); 28877 * } 28878 * $scope.model[value] = ''; 28879 * } 28880 * }; 28881 * }]); 28882 * </file> 28883 * <file name="index.html"> 28884 * <div ng-controller="CancelUpdateController"> 28885 * <p>
28885Both of these inputs are only updated if they are blurred. Hitting escape should 28886 * empty them. Follow these steps and observe the difference:</p> 28887 * <ol> 28888 * <li>Type something in the input. You will see that the model is not yet updated</li> 28889 * <li>Press the Escape key. 28890 * <ol> 28891 * <li> In the first example, nothing happens, because the model is already '', and no 28892 * update is detected. If you blur the input, the model will be set to the current view. 28893 * </li> 28894 * <li> In the second example, the pending update is cancelled, and the input is set back 28895 * to the last committed view value (''). Blurring the input does nothing. 28896 * </li> 28897 * </ol> 28898 * </li> 28899 * </ol> 28900 * 28901 * <form name="myForm" ng-model-options="{ updateOn: 'blur' }"> 28902 * <div> 28903 * <p id="inputDescription1">Without $rollbackViewValue():</p> 28904 * <input name="value1" aria-describedby="inputDescription1" ng-model="model.value1" 28905 * ng-keydown="setEmpty($event, 'value1')"> 28906 * value1: "{{ model.value1 }}" 28907 * </div> 28908 * 28909 * <div> 28910 * <p id="inputDescription2">With $rollbackViewValue():</p> 28911 * <input name="value2" aria-describedby="inputDescription2" ng-model="model.value2" 28912 * ng-keydown="setEmpty($event, 'value2', true)"> 28913 * value2: "{{ model.value2 }}" 28914 * </div> 28915 * </form> 28916 * </div> 28917 * </file> 28918 <file name="style.css"> 28919 div { 28920 display: table-cell; 28921 } 28922 div:nth-child(1) { 28923 padding-right: 30px; 28924 } 28925 28926 </file> 28927 * </example> 28928 */ 28929 $rollbackViewValue: function() { 28930 this.$$timeout.cancel(this.$$pendingDebounce); 28931 this.$viewValue = this.$$lastCommittedViewValue; 28932 this.$render(); 28933 }, 28934 28935 /** 28936 * @ngdoc method 28937 * @name ngModel.NgModelController#$validate 28938 * 28939 * @description 28940 * Runs each of the registered validators (first synchronous validators and then 28941 * asynchronous validators). 28942 * If the validity changes to invalid, the model will be set to `undefined`, 28943 * unless {@link ngModelOptions `ngModelOptions.allowInvalid`} is `true`. 28944 * If the validity changes to valid, it will set the model to the last available valid 28945 * `$modelValue`, i.e. either the last parsed value or the last value set from the scope. 28946 */ 28947 $validate: function() { 28948 // ignore $validate before model is initialized 28949 if (isNumberNaN(this.$modelValue)) { 28950 return; 28951 } 28952 28953 var viewValue = this.$$lastCommittedViewValue; 28954 // Note: we use the $$rawModelValue as $modelValue might have been 28955 // set to undefined during a view -> model update that found validation 28956 // errors. We can't parse the view here, since that could change 28957 // the model although neither viewValue nor the model on the scope changed 28958 var modelValue = this.$$rawModelValue; 28959 28960 var prevValid = this.$valid; 28961 var prevModelValue = this.$modelValue; 28962 28963 var allowInvalid = this.$options.getOption('allowInvalid'); 28964 28965 var that = this; 28966 this.$$runValidators(modelValue, viewValue, function(allValid) { 28967 // If there was no change in validity, don't update the model 28968 // This prevents changing an invalid modelValue to undefined 28969 if (!allowInvalid && prevValid !== allValid) { 28970 // Note: Don't check this.$valid here, as we could have 28971 // external validators (e.g. calculated on the server), 28972 // that just call $setValidity and need the model value 28973 // to calculate their validity. 28974 that.$modelValue = allValid ? modelValue : undefined; 28975 28976 if (that.$modelValue !== prevModelValue) { 28977 that.$$writeModelToScope(); 28978 } 28979 } 28980 }); 28981 }, 28982 28983 $$runValidators: function(modelValue, viewValue, doneCallback) { 28984 this.$$currentValidationRunId++; 28985 var localValidationRunId = this.$$currentValidationRunId; 28986 var that = this; 28987 28988 // check parser error 28989 if (!processParseErrors()) { 28990 validationDone(false); 28991 return; 28992 } 28993 if (!processSyncValidators()) { 28994 validationDone(false); 28995 return; 28996 } 28997 processAsyncValidators(); 28998 28999 function processParseErrors() { 29000 var errorKey = that.$$parserName || 'parse'; 29001 if (isUndefined(that.$$parserValid)) {
vendor: 9,425 bytes, lines 29002-29241
29002 setValidity(errorKey, null); 29003 } else { 29004 if (!that.$$parserValid) { 29005 forEach(that.$validators, function(v, name) { 29006 setValidity(name, null); 29007 }); 29008 forEach(that.$asyncValidators, function(v, name) { 29009 setValidity(name, null); 29010 }); 29011 } 29012 // Set the parse error last, to prevent unsetting it, should a $validators key == parserName 29013 setValidity(errorKey, that.$$parserValid); 29014 return that.$$parserValid; 29015 } 29016 return true; 29017 } 29018 29019 function processSyncValidators() { 29020 var syncValidatorsValid = true; 29021 forEach(that.$validators, function(validator, name) { 29022 var result = Boolean(validator(modelValue, viewValue)); 29023 syncValidatorsValid = syncValidatorsValid && result; 29024 setValidity(name, result); 29025 }); 29026 if (!syncValidatorsValid) { 29027 forEach(that.$asyncValidators, function(v, name) { 29028 setValidity(name, null); 29029 }); 29030 return false; 29031 } 29032 return true; 29033 } 29034 29035 function processAsyncValidators() { 29036 var validatorPromises = []; 29037 var allValid = true; 29038 forEach(that.$asyncValidators, function(validator, name) { 29039 var promise = validator(modelValue, viewValue); 29040 if (!isPromiseLike(promise)) { 29041 throw ngModelMinErr('nopromise', 29042 'Expected asynchronous validator to return a promise but got \'{0}\' instead.', promise); 29043 } 29044 setValidity(name, undefined); 29045 validatorPromises.push(promise.then(function() { 29046 setValidity(name, true); 29047 }, function() { 29048 allValid = false; 29049 setValidity(name, false); 29050 })); 29051 }); 29052 if (!validatorPromises.length) { 29053 validationDone(true); 29054 } else { 29055 that.$$q.all(validatorPromises).then(function() { 29056 validationDone(allValid); 29057 }, noop); 29058 } 29059 } 29060 29061 function setValidity(name, isValid) { 29062 if (localValidationRunId === that.$$currentValidationRunId) { 29063 that.$setValidity(name, isValid); 29064 } 29065 } 29066 29067 function validationDone(allValid) { 29068 if (localValidationRunId === that.$$currentValidationRunId) { 29069 29070 doneCallback(allValid); 29071 } 29072 } 29073 }, 29074 29075 /** 29076 * @ngdoc method 29077 * @name ngModel.NgModelController#$commitViewValue 29078 * 29079 * @description 29080 * Commit a pending update to the `$modelValue`. 29081 * 29082 * Updates may be pending by a debounced event or because the input is waiting for a some future 29083 * event defined in `ng-model-options`. this method is rarely needed as `NgModelController` 29084 * usually handles calling this in response to input events. 29085 */ 29086 $commitViewValue: function() { 29087 var viewValue = this.$viewValue; 29088 29089 this.$$timeout.cancel(this.$$pendingDebounce); 29090 29091 // If the view value has not changed then we should just exit, except in the case where there is 29092 // a native validator on the element. In this case the validation state may have changed even though 29093 // the viewValue has stayed empty. 29094 if (this.$$lastCommittedViewValue === viewValue && (viewValue !== '' || !this.$$hasNativeValidators)) { 29095 return; 29096 } 29097 this.$$updateEmptyClasses(viewValue); 29098 this.$$lastCommittedViewValue = viewValue; 29099 29100 // change to dirty 29101 if (this.$pristine) { 29102 this.$setDirty(); 29103 } 29104 this.$$parseAndValidate(); 29105 }, 29106 29107 $$parseAndValidate: function() { 29108 var viewValue = this.$$lastCommittedViewValue; 29109 var modelValue = viewValue; 29110 var that = this; 29111 29112 this.$$parserValid = isUndefined(modelValue) ? undefined : true; 29113 29114 if (this.$$parserValid) { 29115 for (var i = 0; i < this.$parsers.length; i++) { 29116 modelValue = this.$parsers[i](modelValue); 29117 if (isUndefined(modelValue)) { 29118 this.$$parserValid = false; 29119 break; 29120 } 29121 } 29122 } 29123 if (isNumberNaN(this.$modelValue)) { 29124 // this.$modelValue has not been touched yet... 29125 this.$modelValue = this.$$ngModelGet(this.$$scope); 29126 } 29127 var prevModelValue = this.$modelValue; 29128 var allowInvalid = this.$options.getOption('allowInvalid'); 29129 this.$$rawModelValue = modelValue; 29130 29131 if (allowInvalid) { 29132 this.$modelValue = modelValue; 29133 writeToModelIfNeeded(); 29134 } 29135 29136 // Pass the $$lastCommittedViewValue here, because the cached viewValue might be out of date. 29137 // This can happen if e.g. $setViewValue is called from inside a parser 29138 this.$$runValidators(modelValue, this.$$lastCommittedViewValue, function(allValid) { 29139 if (!allowInvalid) { 29140 // Note: Don't check this.$valid here, as we could have 29141 // external validators (e.g. calculated on the server), 29142 // that just call $setValidity and need the model value 29143 // to calculate their validity. 29144 that.$modelValue = allValid ? modelValue : undefined; 29145 writeToModelIfNeeded(); 29146 } 29147 }); 29148 29149 function writeToModelIfNeeded() { 29150 if (that.$modelValue !== prevModelValue) { 29151 that.$$writeModelToScope(); 29152 } 29153 } 29154 }, 29155 29156 $$writeModelToScope: function() { 29157 this.$$ngModelSet(this.$$scope, this.$modelValue); 29158 forEach(this.$viewChangeListeners, function(listener) { 29159 try { 29160 listener(); 29161 } catch (e) { 29162 // eslint-disable-next-line no-invalid-this 29163 this.$$exceptionHandler(e); 29164 } 29165 }, this); 29166 }, 29167 29168 /** 29169 * @ngdoc method 29170 * @name ngModel.NgModelController#$setViewValue 29171 * 29172 * @description 29173 * Update the view value. 29174 * 29175 * This method should be called when a control wants to change the view value; typically, 29176 * this is done from within a DOM event handler. For example, the {@link ng.directive:input input} 29177 * directive calls it when the value of the input changes and {@link ng.directive:select select} 29178 * calls it when an option is selected. 29179 * 29180 * When `$setViewValue` is called, the new `value` will be staged for committing through the `$parsers` 29181 * and `$validators` pipelines. If there are no special {@link ngModelOptions} specified then the staged 29182 * value is sent directly for processing through the `$parsers` pipeline. After this, the `$validators` and 29183 * `$asyncValidators` are called and the value is applied to `$modelValue`. 29184 * Finally, the value is set to the **expression** specified in the `ng-model` attribute and 29185 * all the registered change listeners, in the `$viewChangeListeners` list are called. 29186 * 29187 * In case the {@link ng.directive:ngModelOptions ngModelOptions} directive is used with `updateOn` 29188 * and the `default` trigger is not listed, all those actions will remain pending until one of the 29189 * `updateOn` events is triggered on the DOM element. 29190 * All these actions will be debounced if the {@link ng.directive:ngModelOptions ngModelOptions} 29191 * directive is used with a custom debounce for this particular event. 29192 * Note that a `$digest` is only triggered once the `updateOn` events are fired, or if `debounce` 29193 * is specified, once the timer runs out. 29194 * 29195 * When used with standard inputs, the view value will always be a string (which is in some cases 29196 * parsed into another type, such as a `Date` object for `input[date]`.) 29197 * However, custom controls might also pass objects to this method. In this case, we should make 29198 * a copy of the object before passing it to `$setViewValue`. This is because `ngModel` does not 29199 * perform a deep watch of objects, it only looks for a change of identity. If you only change 29200 * the property of the object then ngModel will not realize that the object has changed and 29201 * will not invoke the `$parsers` and `$validators` pipelines. For this reason, you should 29202 * not change properties of the copy once it has been passed to `$setViewValue`. 29203 * Otherwise you may cause the model value on the scope to change incorrectly. 29204 * 29205 * <div class="alert alert-info"> 29206 * In any case, the value passed to the method should always reflect the current value 29207 * of the control. For example, if you are calling `$setViewValue` for an input element, 29208 * you should pass the input DOM value. Otherwise, the control and the scope model become 29209 * out of sync. It's also important to note that `$setViewValue` does not call `$render` or change 29210 * the control's DOM value in any way. If we want to change the control's DOM value 29211 * programmatically, we should update the `ngModel` scope expression. Its new value will be 29212 * picked up by the model controller, which will run it through the `$formatters`, `$render` it 29213 * to update the DOM, and finally call `$validate` on it. 29214 * </div> 29215 * 29216 * @param {*} value value from the view. 29217 * @param {string} trigger Event that triggered the update. 29218 */ 29219 $setViewValue: function(value, trigger) { 29220 this.$viewValue = value; 29221 if (this.$options.getOption('updateOnDefault')) { 29222 this.$$debounceViewValueCommit(trigger); 29223 } 29224 }, 29225 29226 $$debounceViewValueCommit: function(trigger) { 29227 var debounceDelay = this.$options.getOption('debounce'); 29228 29229 if (isNumber(debounceDelay[trigger])) { 29230 debounceDelay = debounceDelay[trigger]; 29231 } else if (isNumber(debounceDelay['default'])) { 29232 debounceDelay = debounceDelay['default']; 29233 } 29234 29235 this.$$timeout.cancel(this.$$pendingDebounce); 29236 var that = this; 29237 if (debounceDelay > 0) { // this fails if debounceDelay is an object 29238 this.$$pendingDebounce = this.$$timeout(function() { 29239 that.$commitViewValue(); 29240 }, debounceDelay); 29241 }
29241 else if (this.$$scope.$root.$$phase) { 29242 this.$commitViewValue(); 29243 } else { 29244 this.$$scope.$apply(function() { 29245 that.$commitViewValue(); 29246 }); 29247 } 29248 }, 29249 29250 /** 29251 * @ngdoc method 29252 * 29253 * @name ngModel.NgModelController#$overrideModelOptions 29254 * 29255 * @description 29256 * 29257 * Override the current model options settings programmatically. 29258 * 29259 * The previous `ModelOptions` value will not be modified. Instead, a 29260 * new `ModelOptions` object will inherit from the previous one overriding 29261 * or inheriting settings that are defined in the given parameter. 29262 * 29263 * See {@link ngModelOptions} for information about what options can be specified 29264 * and how model option inheritance works. 29265 * 29266 * @param {Object} options a hash of settings to override the previous options 29267 * 29268 */ 29269 $overrideModelOptions: function(options) { 29270 this.$options = this.$options.createChild(options); 29271 } 29272}; 29273 29274function setupModelWatcher(ctrl) { 29275 // model -> value 29276 // Note: we cannot use a normal scope.$watch as we want to detect the following: 29277 // 1. scope value is 'a' 29278 // 2. user enters 'b' 29279 // 3. ng-change kicks in and reverts scope value to 'a' 29280 // -> scope value did not change since the last digest as 29281 // ng-change executes in apply phase 29282 // 4. view should be changed back to 'a' 29283 ctrl.$$scope.$watch(function ngModelWatch(scope) { 29284 var modelValue = ctrl.$$ngModelGet(scope); 29285 29286 // if scope model value and ngModel value are out of sync 29287 // TODO(perf): why not move this to the action fn? 29288 if (modelValue !== ctrl.$modelValue && 29289 // checks for NaN is needed to allow setting the model to NaN when there's an asyncValidator 29290 // eslint-disable-next-line no-self-compare 29291 (ctrl.$modelValue === ctrl.$modelValue || modelValue === modelValue) 29292 ) { 29293 ctrl.$modelValue = ctrl.$$rawModelValue = modelValue; 29294 ctrl.$$parserValid = undefined; 29295 29296 var formatters = ctrl.$formatters, 29297 idx = formatters.length; 29298 29299 var viewValue = modelValue; 29300 while (idx--) { 29301 viewValue = formatters[idx](viewValue); 29302 } 29303 if (ctrl.$viewValue !== viewValue) { 29304 ctrl.$$updateEmptyClasses(viewValue); 29305 ctrl.$viewValue = ctrl.$$lastCommittedViewValue = viewValue; 29306 ctrl.$render(); 29307 29308 // It is possible that model and view value have been updated during render 29309 ctrl.$$runValidators(ctrl.$modelValue, ctrl.$viewValue, noop); 29310 } 29311 } 29312 29313 return modelValue; 29314 }); 29315} 29316 29317/** 29318 * @ngdoc method 29319 * @name ngModel.NgModelController#$setValidity 29320 * 29321 * @description 29322 * Change the validity state, and notify the form. 29323 * 29324 * This method can be called within $parsers/$formatters or a custom validation implementation. 29325 * However, in most cases it should be sufficient to use the `ngModel.$validators` and 29326 * `ngModel.$asyncValidators` collections which will call `$setValidity` automatically. 29327 * 29328 * @param {string} validationErrorKey Name of the validator. The `validationErrorKey` will be assigned 29329 * to either `$error[validationErrorKey]` or `$pending[validationErrorKey]` 29330 * (for unfulfilled `$asyncValidators`), so that it is available for data-binding. 29331 * The `validationErrorKey` should be in camelCase and will get converted into dash-case 29332 * for class name. Example: `myError` will result in `ng-valid-my-error` and `ng-invalid-my-error` 29333 * classes and can be bound to as `{{ someForm.someControl.$error.myError }}`. 29334 * @param {boolean} isValid Whether the current state is valid (true), invalid (false), pending (undefined), 29335 * or skipped (null). Pending is used for unfulfilled `$asyncValidators`. 29336 * Skipped is used by Angular when validators do not run because of parse errors and 29337 * when `$asyncValidators` do not run because any of the `$validators` failed. 29338 */ 29339addSetValidityMethod({ 29340 clazz: NgModelController, 29341 set: function(object, property) { 29342 object[property] = true; 29343 }, 29344 unset: function(object, property) { 29345 delete object[property]; 29346 } 29347}); 29348 29349 29350/** 29351 * @ngdoc directive 29352 * @name ngModel 29353 * 29354 * @element input 29355 * @priority 1 29356 * 29357 * @description 29358 * The `ngModel` directive binds an `input`,`select`, `textarea` (or custom form control) to a 29359 * property on the scope using {@link ngModel.NgModelController NgModelController}, 29360 * which is created and exposed by this directive. 29361 * 29362 * `ngModel` is responsible for: 29363 * 29364 * - Binding the view into the model, which other directives such as `input`, `textarea` or `select` 29365 * require. 29366 * - Providing validation behavior (i.e. required, number, email, url). 29367 * - Keeping the state of the control (valid/invalid, dirty/pristine, touched/untouched, validation errors). 29368 * - Setting related css classes on the element (`ng-valid`, `ng-invalid`, `ng-dirty`, `ng-pristine`, `ng-touched`, 29369 * `ng-untouched`, `ng-empty`, `ng-not-empty`) including animations. 29370 * - Registering the control with its parent {@link ng.directive:form form}. 29371 *
29372 * Note: `ngModel` will try to bind to the property given by evaluating the expression on the 29373 * current scope. If the property doesn't already exist on this scope, it will be created 29374 * implicitly and added to the scope. 29375 * 29376 * For best practices on using `ngModel`, see: 29377 * 29378 * - [Understanding Scopes](https://github.com/angular/angular.js/wiki/Understanding-Scopes) 29379 * 29380 * For basic examples, how to use `ngModel`, see: 29381 * 29382 * - {@link ng.directive:input input} 29383 * - {@link input[text] text} 29384 * - {@link input[checkbox] checkbox} 29385 * - {@link input[radio] radio} 29386 * - {@link input[number] number} 29387 * - {@link input[email] email} 29388 * - {@link input[url] url} 29389 * - {@link input[date] date} 29390 * - {@link input[datetime-local] datetime-local} 29391 * - {@link input[time] time} 29392 * - {@link input[month] month} 29393 * - {@link input[week] week} 29394 * - {@link ng.directive:select select} 29395 * - {@link ng.directive:textarea textarea} 29396 * 29397 * # Complex Models (objects or collections) 29398 * 29399 * By default, `ngModel` watches the model by reference, not value. This is important to know when 29400 * binding inputs to models that are objects (e.g. `Date`) or collections (e.g. arrays). If only properties of the 29401 * object or collection change, `ngModel` will not be notified and so the input will not be re-rendered. 29402 * 29403 * The model must be assigned an entirely new object or collection before a re-rendering will occur. 29404 * 29405 * Some directives have options that will cause them to use a custom `$watchCollection` on the model expression 29406 * - for example, `ngOptions` will do so when a `track by` clause is included in the comprehension expression or 29407 * if the select is given the `multiple` attribute. 29408 * 29409 * The `$watchCollection()` method only does a shallow comparison, meaning that changing properties deeper than the 29410 * first level of the object (or only changing the properties of an item in the collection if it's an array) will still 29411 * not trigger a re-rendering of the model. 29412 * 29413 * # CSS classes 29414 * The following CSS classes are added and removed on the associated input/select/textarea element 29415 * depending on the validity of the model. 29416 * 29417 * - `ng-valid`: the model is valid 29418 * - `ng-invalid`: the model is invalid 29419 * - `ng-valid-[key]`: for each valid key added by `$setValidity` 29420 * - `ng-invalid-[key]`: for each invalid key added by `$setValidity` 29421 * - `ng-pristine`: the control hasn't been interacted with yet 29422 * - `ng-dirty`: the control has been interacted with 29423 * - `ng-touched`: the control has been blurred 29424 * - `ng-untouched`: the control hasn't been blurred 29425 * - `ng-pending`: any `$asyncValidators` are unfulfilled 29426 * - `ng-empty`: the view does not contain a value or the value is deemed "empty", as defined 29427 * by the {@link ngModel.NgModelController#$isEmpty} method 29428 * - `ng-not-empty`: the view contains a non-empty value 29429 * 29430 * Keep in mind that ngAnimate can detect each of these classes when added and removed. 29431 * 29432 * ## Animation Hooks 29433 * 29434 * Animations within models are triggered when any of the associated CSS classes are added and removed 29435 * on the input element which is attached to the model. These classes include: `.ng-pristine`, `.ng-dirty`, 29436 * `.ng-invalid` and `.ng-valid` as well as any other validations that are performed on the model itself. 29437 * The animations that are triggered within ngModel are similar to how they work in ngClass and 29438 * animations can be hooked into using CSS transitions, keyframes as well as JS animations. 29439 * 29440 * The following example shows a simple way to utilize CSS transitions to style an input element 29441 * that has been rendered as invalid after it has been validated: 29442 * 29443 * <pre> 29444 * //be sure to include ngAnimate as a module to hook into more 29445 * //advanced animations 29446 * .my-input { 29447 * transition:0.5s linear all; 29448 * background: white; 29449 * } 29450 * .my-input.ng-invalid { 29451 * background: red; 29452 * color:white; 29453 * } 29454 * </pre> 29455 * 29456 * @example 29457 * <example deps="angular-animate.js" animations="true" fixBase="true" module="inputExample" name="ng-model"> 29458 <file name="index.html"> 29459 <script> 29460 angular.module('inputExample', [])
29461 .controller('ExampleController', ['$scope', function($scope) { 29462 $scope.val = '1'; 29463 }]); 29464 </script> 29465 <style> 29466 .my-input { 29467 transition:all linear 0.5s; 29468 background: transparent; 29469 } 29470 .my-input.ng-invalid { 29471 color:white; 29472 background: red; 29473 } 29474 </style> 29475 <p id="inputDescription"> 29476 Update input to see transitions when valid/invalid. 29477 Integer is a valid value. 29478 </p> 29479 <form name="testForm" ng-controller="ExampleController"> 29480 <input ng-model="val" ng-pattern="/^\d+$/" name="anim" class="my-input" 29481 aria-describedby="inputDescription" /> 29482 </form> 29483 </file> 29484 * </example> 29485 * 29486 * ## Binding to a getter/setter 29487 * 29488 * Sometimes it's helpful to bind `ngModel` to a getter/setter function. A getter/setter is a 29489 * function that returns a representation of the model when called with zero arguments, and sets 29490 * the internal state of a model when called with an argument. It's sometimes useful to use this 29491 * for models that have an internal representation that's different from what the model exposes 29492 * to the view. 29493 * 29494 * <div class="alert alert-success"> 29495 * **Best Practice:** It's best to keep getters fast because Angular is likely to call them more 29496 * frequently than other parts of your code. 29497 * </div> 29498 * 29499 * You use this behavior by adding `ng-model-options="{ getterSetter: true }"` to an element that 29500 * has `ng-model` attached to it. You can also add `ng-model-options="{ getterSetter: true }"` to 29501 * a `<form>`, which will enable this behavior for all `<input>`s within it. See 29502 * {@link ng.directive:ngModelOptions `ngModelOptions`} for more. 29503 * 29504 * The following example shows how to use `ngModel` with a getter/setter: 29505 * 29506 * @example 29507 * <example name="ngModel-getter-setter" module="getterSetterExample"> 29508 <file name="index.html">
29509 <div ng-controller="ExampleController"> 29510 <form name="userForm"> 29511 <label>Name: 29512 <input type="text" name="userName" 29513 ng-model="user.name" 29514 ng-model-options="{ getterSetter: true }" /> 29515 </label> 29516 </form> 29517 <pre>user.name = <span ng-bind="user.name()"></span></pre> 29518 </div> 29519 </file> 29520 <file name="app.js"> 29521 angular.module('getterSetterExample', []) 29522 .controller('ExampleController', ['$scope', function($scope) { 29523 var _name = 'Brian'; 29524 $scope.user = { 29525 name: function(newName) { 29526 // Note that newName can be undefined for two reasons: 29527 // 1. Because it is called as a getter and thus called with no arguments 29528 // 2. Because the property should actually be set to undefined. This happens e.g. if the 29529 // input is invalid 29530 return arguments.length ? (_name = newName) : _name; 29531 } 29532 }; 29533 }]); 29534 </file> 29535 * </example> 29536 */ 29537var ngModelDirective = ['$rootScope', function($rootScope) { 29538 return { 29539 restrict: 'A', 29540 require: ['ngModel', '^?form', '^?ngModelOptions'], 29541 controller: NgModelController, 29542 // Prelink needs to run before any input directive 29543 // so that we can set the NgModelOptions in NgModelController 29544 // before anyone else uses it. 29545 priority: 1, 29546 compile: function ngModelCompile(element) { 29547 // Setup initial state of the control 29548 element.addClass(PRISTINE_CLASS).addClass(UNTOUCHED_CLASS).addClass(VALID_CLASS); 29549 29550 return { 29551 pre: function ngModelPreLink(scope, element, attr, ctrls) { 29552 var modelCtrl = ctrls[0], 29553 formCtrl = ctrls[1] || modelCtrl.$$parentForm, 29554 optionsCtrl = ctrls[2]; 29555 29556 if (optionsCtrl) { 29557 modelCtrl.$options = optionsCtrl.$options; 29558 } 29559 29560 modelCtrl.$$initGetterSetters(); 29561 29562 // notify others, especially parent forms 29563 formCtrl.$addControl(modelCtrl); 29564 29565 attr.$observe('name', function(newValue) { 29566 if (modelCtrl.$name !== newValue) { 29567 modelCtrl.$$parentForm.$$renameControl(modelCtrl, newValue); 29568 } 29569 }); 29570 29571 scope.$on('$destroy', function() { 29572 modelCtrl.$$parentForm.$removeControl(modelCtrl); 29573 }); 29574 }, 29575 post: function ngModelPostLink(scope, element, attr, ctrls) { 29576 var modelCtrl = ctrls[0]; 29577 if (modelCtrl.$options.getOption('updateOn')) { 29578 element.on(modelCtrl.$options.getOption('updateOn'), function(ev) { 29579 modelCtrl.$$debounceViewValueCommit(ev && ev.type); 29580 }); 29581 } 29582 29583 function setTouched() { 29584 modelCtrl.$setTouched(); 29585 } 29586 29587 element.on('blur', function() { 29588 if (modelCtrl.$touched) return; 29589 29590 if ($rootScope.$$phase) { 29591 scope.$evalAsync(setTouched); 29592 } else { 29593 scope.$apply(setTouched); 29594 } 29595 }); 29596 } 29597 }; 29598 } 29599 }; 29600}]; 29601 29602/* exported defaultModelOptions */ 29603var defaultModelOptions; 29604var DEFAULT_REGEXP = /(\s+|^)default(\s+|$)/; 29605 29606/** 29607 * @ngdoc type 29608 * @name ModelOptions 29609 * @description 29610 * A container for the options set by the {@link ngModelOptions} directive 29611 */ 29612function ModelOptions(options) { 29613 this.$$options = options; 29614} 29615 29616ModelOptions.prototype = { 29617 29618 /** 29619 * @ngdoc method 29620 * @name ModelOptions#getOption 29621 * @param {string} name the name of the option to retrieve 29622 * @returns {*} the value of the option 29623 * @description 29624 * Returns the value of the given option 29625 */ 29626 getOption: function(name) { 29627 return this.$$options[name]; 29628 }, 29629 29630 /** 29631 * @ngdoc method 29632 * @name ModelOptions#createChild 29633 * @param {Object} options a hash of options for the new child that will override the parent's options 29634 * @return {ModelOptions} a new `ModelOptions` object initialized with the given options. 29635 */ 29636 createChild: function(options) { 29637 var inheritAll = false; 29638 29639 // make a shallow copy 29640 options = extend({}, options); 29641 29642 // Inherit options from the parent if specified by the value `"$inherit"`
vendor: 5,565 bytes, lines 29643-29782
29643 forEach(options, /* @this */ function(option, key) { 29644 if (option === '$inherit') { 29645 if (key === '*') { 29646 inheritAll = true; 29647 } else { 29648 options[key] = this.$$options[key]; 29649 // `updateOn` is special so we must also inherit the `updateOnDefault` option 29650 if (key === 'updateOn') { 29651 options.updateOnDefault = this.$$options.updateOnDefault; 29652 } 29653 } 29654 } else { 29655 if (key === 'updateOn') { 29656 // If the `updateOn` property contains the `default` event then we have to remove 29657 // it from the event list and set the `updateOnDefault` flag. 29658 options.updateOnDefault = false; 29659 options[key] = trim(option.replace(DEFAULT_REGEXP, function() { 29660 options.updateOnDefault = true; 29661 return ' '; 29662 })); 29663 } 29664 } 29665 }, this); 29666 29667 if (inheritAll) { 29668 // We have a property of the form: `"*": "$inherit"` 29669 delete options['*']; 29670 defaults(options, this.$$options); 29671 } 29672 29673 // Finally add in any missing defaults 29674 defaults(options, defaultModelOptions.$$options); 29675 29676 return new ModelOptions(options); 29677 } 29678}; 29679 29680 29681defaultModelOptions = new ModelOptions({ 29682 updateOn: '', 29683 updateOnDefault: true, 29684 debounce: 0, 29685 getterSetter: false, 29686 allowInvalid: false, 29687 timezone: null 29688}); 29689 29690 29691/** 29692 * @ngdoc directive 29693 * @name ngModelOptions 29694 * 29695 * @description 29696 * This directive allows you to modify the behaviour of {@link ngModel} directives within your 29697 * application. You can specify an `ngModelOptions` directive on any element. All {@link ngModel} 29698 * directives will use the options of their nearest `ngModelOptions` ancestor. 29699 * 29700 * The `ngModelOptions` settings are found by evaluating the value of the attribute directive as 29701 * an Angular expression. This expression should evaluate to an object, whose properties contain 29702 * the settings. For example: `<div "ng-model-options"="{ debounce: 100 }"`. 29703 * 29704 * ## Inheriting Options 29705 * 29706 * You can specify that an `ngModelOptions` setting should be inherited from a parent `ngModelOptions` 29707 * directive by giving it the value of `"$inherit"`. 29708 * Then it will inherit that setting from the first `ngModelOptions` directive found by traversing up the 29709 * DOM tree. If there is no ancestor element containing an `ngModelOptions` directive then default settings 29710 * will be used. 29711 * 29712 * For example given the following fragment of HTML 29713 * 29714 * 29715 * ```html 29716 * <div ng-model-options="{ allowInvalid: true, debounce: 200 }"> 29717 * <form ng-model-options="{ updateOn: 'blur', allowInvalid: '$inherit' }"> 29718 * <input ng-model-options="{ updateOn: 'default', allowInvalid: '$inherit' }" /> 29719 * </form> 29720 * </div> 29721 * ``` 29722 * 29723 * the `input` element will have the following settings 29724 * 29725 * ```js 29726 * { allowInvalid: true, updateOn: 'default', debounce: 0 } 29727 * ``` 29728 * 29729 * Notice that the `debounce` setting was not inherited and used the default value instead. 29730 * 29731 * You can specify that all undefined settings are automatically inherited from an ancestor by 29732 * including a property with key of `"*"` and value of `"$inherit"`. 29733 * 29734 * For example given the following fragment of HTML 29735 * 29736 * 29737 * ```html 29738 * <div ng-model-options="{ allowInvalid: true, debounce: 200 }"> 29739 * <form ng-model-options="{ updateOn: 'blur', "*": '$inherit' }"> 29740 * <input ng-model-options="{ updateOn: 'default', "*": '$inherit' }" /> 29741 * </form> 29742 * </div> 29743 * ``` 29744 * 29745 * the `input` element will have the following settings 29746 * 29747 * ```js 29748 * { allowInvalid: true, updateOn: 'default', debounce: 200 } 29749 * ``` 29750 * 29751 * Notice that the `debounce` setting now inherits the value from the outer `<div>` element. 29752 * 29753 * If you are creating a reusable component then you should be careful when using `"*": "$inherit"` 29754 * since you may inadvertently inherit a setting in the future that changes the behavior of your component. 29755 * 29756 * 29757 * ## Triggering and debouncing model updates 29758 * 29759 * The `updateOn` and `debounce` properties allow you to specify a custom list of events that will 29760 * trigger a model update and/or a debouncing delay so that the actual update only takes place when 29761 * a timer expires; this timer will be reset after another change takes place. 29762 * 29763 * Given the nature of `ngModelOptions`, the value displayed inside input fields in the view might 29764 * be different from the value in the actual model. This means that if you update the model you 29765 * should also invoke {@link ngModel.NgModelController#$rollbackViewValue} on the relevant input field in 29766 * order to make sure it is synchronized with the model and that any debounced action is canceled. 29767 * 29768 * The easiest way to reference the control's {@link ngModel.NgModelController#$rollbackViewValue} 29769 * method is by making sure the input is placed inside a form that has a `name` attribute. This is 29770 * important because `form` controllers are published to the related scope under the name in their 29771 * `name` attribute. 29772 * 29773 * Any pending changes will take place immediately when an enclosing form is submitted via the 29774 * `submit` event. Note that `ngClick` events will occur before the model is updated. Use `ngSubmit` 29775 * to have access to the updated model. 29776 * 29777 * The following example shows how to override immediate updates. Changes on the inputs within the 29778 * form will update the model only when the control loses focus (blur event). If `escape` key is 29779 * pressed while the input field is focused, the value is reset to the value in the current model. 29780 * 29781 * <example name="ngModelOptions-directive-blur" module="optionsExample"> 29782 * <file name="index.html">
29783 * <div ng-controller="ExampleController"> 29784 * <form name="userForm"> 29785 * <label> 29786 * Name: 29787 * <input type="text" name="userName" 29788 * ng-model="user.name" 29789 * ng-model-options="{ updateOn: 'blur' }" 29790 * ng-keyup="cancel($event)" /> 29791 * </label><br /> 29792 * <label> 29793 * Other data: 29794 * <input type="text" ng-model="user.data" /> 29795 * </label><br /> 29796 * </form> 29797 * <pre>user.name = <span ng-bind="user.name"></span></pre> 29798 * </div> 29799 * </file> 29800 * <file name="app.js"> 29801 * angular.module('optionsExample', []) 29802 * .controller('ExampleController', ['$scope', function($scope) { 29803 * $scope.user = { name: 'say', data: '' }; 29804 * 29805 * $scope.cancel = function(e) { 29806 * if (e.keyCode === 27) { 29807 * $scope.userForm.userName.$rollbackViewValue(); 29808 * } 29809 * }; 29810 * }]); 29811 * </file> 29812 * <file name="protractor.js" type="protractor"> 29813 * var model = element(by.binding('user.name')); 29814 * var input = element(by.model('user.name')); 29815 * var other = element(by.model('user.data')); 29816 * 29817 * it('should allow custom events', function() { 29818 * input.sendKeys(' hello'); 29819 * input.click(); 29820 * expect(model.getText()).toEqual('say'); 29821 * other.click(); 29822 * expect(model.getText()).toEqual('say hello'); 29823 * }); 29824 * 29825 * it('should $rollbackViewValue when model changes', function() { 29826 * input.sendKeys(' hello'); 29827 * expect(input.getAttribute('value')).toEqual('say hello'); 29828 * input.sendKeys(protractor.Key.ESCAPE); 29829 * expect(input.getAttribute('value')).toEqual('say'); 29830 * other.click(); 29831 * expect(model.getText()).toEqual('say'); 29832 * }); 29833 * </file> 29834 * </example> 29835 * 29836 * The next example shows how to debounce model changes. Model will be updated only 1 sec after last change. 29837 * If the `Clear` button is pressed, any debounced action is canceled and the value becomes empty. 29838 * 29839 * <example name="ngModelOptions-directive-debounce" module="optionsExample"> 29840 * <file name="index.html">
29841 * <div ng-controller="ExampleController"> 29842 * <form name="userForm"> 29843 * Name: 29844 * <input type="text" name="userName" 29845 * ng-model="user.name" 29846 * ng-model-options="{ debounce: 1000 }" /> 29847 * <button ng-click="userForm.userName.$rollbackViewValue(); user.name=''">Clear</button><br /> 29848 * </form> 29849 * <pre>user.name = <span ng-bind="user.name"></span></pre> 29850 * </div> 29851 * </file> 29852 * <file name="app.js"> 29853 * angular.module('optionsExample', []) 29854 * .controller('ExampleController', ['$scope', function($scope) { 29855 * $scope.user = { name: 'say' }; 29856 * }]); 29857 * </file> 29858 * </example> 29859 * 29860 * ## Model updates and validation 29861 * 29862 * The default behaviour in `ngModel` is that the model value is set to `undefined` when the 29863 * validation determines that the value is invalid. By setting the `allowInvalid` property to true, 29864 * the model will still be updated even if the value is invalid. 29865 * 29866 * 29867 * ## Connecting to the scope 29868 * 29869 * By setting the `getterSetter` property to true you are telling ngModel that the `ngModel` expression 29870 * on the scope refers to a "getter/setter" function rather than the value itself. 29871 * 29872 * The following example shows how to bind to getter/setters: 29873 * 29874 * <example name="ngModelOptions-directive-getter-setter" module="getterSetterExample"> 29875 * <file name="index.html">
29876 * <div ng-controller="ExampleController"> 29877 * <form name="userForm"> 29878 * <label> 29879 * Name: 29880 * <input type="text" name="userName" 29881 * ng-model="user.name" 29882 * ng-model-options="{ getterSetter: true }" /> 29883 * </label> 29884 * </form> 29885 * <pre>user.name = <span ng-bind="user.name()"></span></pre> 29886 * </div> 29887 * </file> 29888 * <file name="app.js"> 29889 * angular.module('getterSetterExample', []) 29890 * .controller('ExampleController', ['$scope', function($scope) { 29891 * var _name = 'Brian'; 29892 * $scope.user = { 29893 * name: function(newName) { 29894 * return angular.isDefined(newName) ? (_name = newName) : _name; 29895 * } 29896 * }; 29897 * }]); 29898 * </file> 29899 * </example> 29900 * 29901 * 29902 * ## Specifying timezones 29903 * 29904 * You can specify the timezone that date/time input directives expect by providing its name in the 29905 * `timezone` property. 29906 * 29907 * @param {Object} ngModelOptions options to apply to {@link ngModel} directives on this element and 29908 * and its descendents. Valid keys are: 29909 * - `updateOn`: string specifying which event should the input be bound to. You can set several 29910 * events using an space delimited list. There is a special event called `default` that 29911 * matches the default events belonging to the control. 29912 * - `debounce`: integer value which contains the debounce model update value in milliseconds. A 29913 * value of 0 triggers an immediate update. If an object is supplied instead, you can specify a 29914 * custom value for each event. For example: 29915 * ``` 29916 * ng-model-options="{ 29917 * updateOn: 'default blur', 29918 * debounce: { 'default': 500, 'blur': 0 } 29919 * }" 29920 * ``` 29921 * - `allowInvalid`: boolean value which indicates that the model can be set with values that did 29922 * not validate correctly instead of the default behavior of setting the model to undefined. 29923 * - `getterSetter`: boolean value which determines whether or not to treat functions bound to 29924 * `ngModel` as getters/setters. 29925 * - `timezone`: Defines the timezone to be used to read/write the `Date` instance in the model for 29926 * `<input type="date" />`, `<input type="time" />`, ... . It understands UTC/GMT and the 29927 * continental US time zone abbreviations, but for general use, use a time zone offset, for 29928 * example, `'+0430'` (4 hours, 30 minutes east of the Greenwich meridian) 29929 * If not specified, the timezone of the browser will be used. 29930 * 29931 */ 29932var ngModelOptionsDirective = function() { 29933 NgModelOptionsController.$inject = ['$attrs', '$scope']; 29934 function NgModelOptionsController($attrs, $scope) { 29935 this.$$attrs = $attrs; 29936 this.$$scope = $scope; 29937 } 29938 NgModelOptionsController.prototype = { 29939 $onInit: function() { 29940 var parentOptions = this.parentCtrl ? this.parentCtrl.$options : defaultModelOptions; 29941 var modelOptionsDefinition = this.$$scope.$eval(this.$$attrs.ngModelOptions); 29942 29943 this.$options = parentOptions.createChild(modelOptionsDefinition); 29944 } 29945 }; 29946 29947 return { 29948 restrict: 'A', 29949 // ngModelOptions needs to run before ngModel and input directives 29950 priority: 10, 29951 require: {parentCtrl: '?^^ngModelOptions'}, 29952 bindToController: true, 29953 controller: NgModelOptionsController 29954 }; 29955}; 29956 29957 29958// shallow copy over values from `src` that are not already specified on `dst` 29959function defaults(dst, src) { 29960 forEach(src, function(value, key) { 29961 if (!isDefined(dst[key])) { 29962 dst[key] = value; 29963 } 29964 }); 29965} 29966 29967/** 29968 * @ngdoc directive 29969 * @name ngNonBindable 29970 * @restrict AC 29971 * @priority 1000 29972 * 29973 * @description 29974 * The `ngNonBindable` directive tells Angular not to compile or bind the contents of the current 29975 * DOM element. This is useful if the element contains what appears to be Angular directives and 29976 * bindings but which should be ignored by Angular. This could be the case if you have a site that 29977 * displays snippets of code, for instance. 29978 * 29979 * @element ANY 29980 * 29981 * @example 29982 * In this example there are two locations where a simple interpolation binding (`{{}}`) is present, 29983 * but the one wrapped in `ngNonBindable` is left alone. 29984 * 29985 * @example 29986 <example name="ng-non-bindable"> 29987 <file name="index.html"> 29988 <div>Normal: {{1 + 2}}</div> 29989 <div ng-non-bindable>Ignored: {{1 + 2}}</div> 29990 </file> 29991 <file name="protractor.js" type="protractor"> 29992 it('should check ng-non-bindable', function() { 29993 expect(element(by.binding('1 + 2')).getText()).toContain('3');
29994 expect(element.all(by.css('div')).last().getText()).toMatch(/1 \+ 2/); 29995 }); 29996 </file> 29997
vendor: 30,784 bytes, lines 29997-30725
29997 </example> 29998 */ 29999var ngNonBindableDirective = ngDirective({ terminal: true, priority: 1000 }); 30000 30001/* exported ngOptionsDirective */ 30002 30003/* global jqLiteRemove */ 30004 30005var ngOptionsMinErr = minErr('ngOptions'); 30006 30007/** 30008 * @ngdoc directive 30009 * @name ngOptions 30010 * @restrict A 30011 * 30012 * @description 30013 * 30014 * The `ngOptions` attribute can be used to dynamically generate a list of `<option>` 30015 * elements for the `<select>` element using the array or object obtained by evaluating the 30016 * `ngOptions` comprehension expression. 30017 * 30018 * In many cases, {@link ng.directive:ngRepeat ngRepeat} can be used on `<option>` elements instead of 30019 * `ngOptions` to achieve a similar result. However, `ngOptions` provides some benefits: 30020 * - more flexibility in how the `<select>`'s model is assigned via the `select` **`as`** part of the 30021 * comprehension expression 30022 * - reduced memory consumption by not creating a new scope for each repeated instance 30023 * - increased render speed by creating the options in a documentFragment instead of individually 30024 * 30025 * When an item in the `<select>` menu is selected, the array element or object property 30026 * represented by the selected option will be bound to the model identified by the `ngModel` 30027 * directive. 30028 * 30029 * Optionally, a single hard-coded `<option>` element, with the value set to an empty string, can 30030 * be nested into the `<select>` element. This element will then represent the `null` or "not selected" 30031 * option. See example below for demonstration. 30032 * 30033 * ## Complex Models (objects or collections) 30034 * 30035 * By default, `ngModel` watches the model by reference, not value. This is important to know when 30036 * binding the select to a model that is an object or a collection. 30037 * 30038 * One issue occurs if you want to preselect an option. For example, if you set 30039 * the model to an object that is equal to an object in your collection, `ngOptions` won't be able to set the selection, 30040 * because the objects are not identical. So by default, you should always reference the item in your collection 30041 * for preselections, e.g.: `$scope.selected = $scope.collection[3]`. 30042 * 30043 * Another solution is to use a `track by` clause, because then `ngOptions` will track the identity 30044 * of the item not by reference, but by the result of the `track by` expression. For example, if your 30045 * collection items have an id property, you would `track by item.id`. 30046 * 30047 * A different issue with objects or collections is that ngModel won't detect if an object property or 30048 * a collection item changes. For that reason, `ngOptions` additionally watches the model using 30049 * `$watchCollection`, when the expression contains a `track by` clause or the the select has the `multiple` attribute. 30050 * This allows ngOptions to trigger a re-rendering of the options even if the actual object/collection 30051 * has not changed identity, but only a property on the object or an item in the collection changes. 30052 * 30053 * Note that `$watchCollection` does a shallow comparison of the properties of the object (or the items in the collection 30054 * if the model is an array). This means that changing a property deeper than the first level inside the 30055 * object/collection will not trigger a re-rendering. 30056 * 30057 * ## `select` **`as`** 30058 * 30059 * Using `select` **`as`** will bind the result of the `select` expression to the model, but 30060 * the value of the `<select>` and `<option>` html elements will be either the index (for array data sources) 30061 * or property name (for object data sources) of the value within the collection. If a **`track by`** expression 30062 * is used, the result of that expression will be set as the value of the `option` and `select` elements. 30063 * 30064 * 30065 * ### `select` **`as`** and **`track by`** 30066 * 30067 * <div class="alert alert-warning"> 30068 * Be careful when using `select` **`as`** and **`track by`** in the same expression. 30069 * </div> 30070 * 30071 * Given this array of items on the $scope: 30072 * 30073 * ```js 30074 * $scope.items = [{ 30075 * id: 1, 30076 * label: 'aLabel', 30077 * subItem: { name: 'aSubItem' } 30078 * }, { 30079 * id: 2, 30080 * label: 'bLabel', 30081 * subItem: { name: 'bSubItem' } 30082 * }]; 30083 * ``` 30084 * 30085 * This will work: 30086 * 30087 * ```html 30088 * <select ng-options="item as item.label for item in items track by item.id" ng-model="selected"></select> 30089 * ``` 30090 * ```js 30091 * $scope.selected = $scope.items[0]; 30092 * ``` 30093 * 30094 * but this will not work: 30095 * 30096 * ```html 30097 * <select ng-options="item.subItem as item.label for item in items track by item.id" ng-model="selected"></select> 30098 * ``` 30099 * ```js 30100 * $scope.selected = $scope.items[0].subItem; 30101 * ``` 30102 * 30103 * In both examples, the **`track by`** expression is applied successfully to each `item` in the 30104 * `items` array. Because the selected option has been set programmatically in the controller, the 30105 * **`track by`** expression is also applied to the `ngModel` value. In the first example, the 30106 * `ngModel` value is `items[0]` and the **`track by`** expression evaluates to `items[0].id` with 30107 * no issue. In the second example, the `ngModel` value is `items[0].subItem` and the **`track by`** 30108 * expression evaluates to `items[0].subItem.id` (which is undefined). As a result, the model value 30109 * is not matched against any `<option>` and the `<select>` appears as having no selected value. 30110 * 30111 * 30112 * @param {string} ngModel Assignable AngularJS expression to data-bind to. 30113 * @param {comprehension_expression} ngOptions in one of the following forms: 30114 * 30115 * * for array data sources: 30116 * * `label` **`for`** `value` **`in`** `array` 30117 * * `select` **`as`** `label` **`for`** `value` **`in`** `array` 30118 * * `label` **`group by`** `group` **`for`** `value` **`in`** `array` 30119 * * `label` **`disable when`** `disable` **`for`** `value` **`in`** `array` 30120 * * `label` **`group by`** `group` **`for`** `value` **`in`** `array` **`track by`** `trackexpr` 30121 * * `label` **`disable when`** `disable` **`for`** `value` **`in`** `array` **`track by`** `trackexpr` 30122 * * `label` **`for`** `value` **`in`** `array` | orderBy:`orderexpr` **`track by`** `trackexpr` 30123 * (for including a filter with `track by`) 30124 * * for object data sources: 30125 * * `label` **`for (`**`key` **`,`** `value`**`) in`** `object` 30126 * * `select` **`as`** `label` **`for (`**`key` **`,`** `value`**`) in`** `object` 30127 * * `label` **`group by`** `group` **`for (`**`key`**`,`** `value`**`) in`** `object` 30128 * * `label` **`disable when`** `disable` **`for (`**`key`**`,`** `value`**`) in`** `object` 30129 * * `select` **`as`** `label` **`group by`** `group` 30130 * **`for` `(`**`key`**`,`** `value`**`) in`** `object` 30131 * * `select` **`as`** `label` **`disable when`** `disable` 30132 * **`for` `(`**`key`**`,`** `value`**`) in`** `object` 30133 * 30134 * Where: 30135 * 30136 * * `array` / `object`: an expression which evaluates to an array / object to iterate over. 30137 * * `value`: local variable which will refer to each item in the `array` or each property value 30138 * of `object` during iteration. 30139 * * `key`: local variable which will refer to a property name in `object` during iteration. 30140 * * `label`: The result of this expression will be the label for `<option>` element. The 30141 * `expression` will most likely refer to the `value` variable (e.g. `value.propertyName`). 30142 * * `select`: The result of this expression will be bound to the model of the parent `<select>` 30143 * element. If not specified, `select` expression will default to `value`. 30144 * * `group`: The result of this expression will be used to group options using the `<optgroup>` 30145 * DOM element. 30146 * * `disable`: The result of this expression will be used to disable the rendered `<option>` 30147 * element. Return `true` to disable. 30148 * * `trackexpr`: Used when working with an array of objects. The result of this expression will be 30149 * used to identify the objects in the array. The `trackexpr` will most likely refer to the 30150 * `value` variable (e.g. `value.propertyName`). With this the selection is preserved 30151 * even when the options are recreated (e.g. reloaded from the server). 30152 * @param {string=} name Property name of the form under which the control is published. 30153 * @param {string=} required The control is considered valid only if value is entered. 30154 * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to 30155 * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of 30156 * `required` when you want to data-bind to the `required` attribute. 30157 * @param {string=} ngAttrSize sets the size of the select element dynamically. Uses the 30158 * {@link guide/interpolation#-ngattr-for-binding-to-arbitrary-attributes ngAttr} directive. 30159 * 30160 * @example 30161 <example module="selectExample" name="select"> 30162 <file name="index.html"> 30163 <script> 30164 angular.module('selectExample', []) 30165 .controller('ExampleController', ['$scope', function($scope) { 30166 $scope.colors = [ 30167 {name:'black', shade:'dark'}, 30168 {name:'white', shade:'light', notAnOption: true}, 30169 {name:'red', shade:'dark'}, 30170 {name:'blue', shade:'dark', notAnOption: true}, 30171 {name:'yellow', shade:'light', notAnOption: false} 30172 ]; 30173 $scope.myColor = $scope.colors[2]; // red 30174 }]); 30175 </script> 30176 <div ng-controller="ExampleController"> 30177 <ul> 30178 <li ng-repeat="color in colors"> 30179 <label>Name: <input ng-model="color.name"></label> 30180 <label><input type="checkbox" ng-model="color.notAnOption"> Disabled?</label> 30181 <button ng-click="colors.splice($index, 1)" aria-label="Remove">X</button> 30182 </li> 30183 <li> 30184 <button ng-click="colors.push({})">add</button> 30185 </li> 30186 </ul> 30187 <hr/> 30188 <label>Color (null not allowed): 30189 <select ng-model="myColor" ng-options="color.name for color in colors"></select> 30190 </label><br/> 30191 <label>Color (null allowed): 30192 <span class="nullable"> 30193 <select ng-model="myColor" ng-options="color.name for color in colors"> 30194 <option value="">-- choose color --</option> 30195 </select> 30196 </span></label><br/> 30197 30198 <label>Color grouped by shade: 30199 <select ng-model="myColor" ng-options="color.name group by color.shade for color in colors"> 30200 </select> 30201 </label><br/> 30202 30203 <label>Color grouped by shade, with some disabled: 30204 <select ng-model="myColor" 30205 ng-options="color.name group by color.shade disable when color.notAnOption for color in colors"> 30206 </select> 30207 </label><br/> 30208 30209 30210 30211 Select <button ng-click="myColor = { name:'not in list', shade: 'other' }">bogus</button>. 30212 <br/> 30213 <hr/> 30214 Currently selected: {{ {selected_color:myColor} }} 30215 <div style="border:solid 1px black; height:20px" 30216 ng-style="{'background-color':myColor.name}"> 30217 </div> 30218 </div> 30219 </file> 30220 <file name="protractor.js" type="protractor"> 30221 it('should check ng-options', function() { 30222 expect(element(by.binding('{selected_color:myColor}')).getText()).toMatch('red'); 30223 element.all(by.model('myColor')).first().click(); 30224 element.all(by.css('select[ng-model="myColor"] option')).first().click(); 30225 expect(element(by.binding('{selected_color:myColor}')).getText()).toMatch('black'); 30226 element(by.css('.nullable select[ng-model="myColor"]')).click(); 30227 element.all(by.css('.nullable select[ng-model="myColor"] option')).first().click(); 30228 expect(element(by.binding('{selected_color:myColor}')).getText()).toMatch('null'); 30229 }); 30230 </file> 30231 </example> 30232 */ 30233 30234/* eslint-disable max-len */ 30235// //00001111111111000000000002222222222000000000000000000000333333333300000000000000000000000004444444444400000000000005555555555555000000000666666666666600000007777777777777000000000000000888888888800000000000000000009999999999 30236var 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]+?))?$/; 30237 // 1: value expression (valueFn) 30238 // 2: label expression (displayFn) 30239 // 3: group by expression (groupByFn) 30240 // 4: disable when expression (disableWhenFn) 30241 // 5: array item variable name 30242 // 6: object item key variable name 30243 // 7: object item value variable name 30244 // 8: collection expression 30245 // 9: track by expression 30246/* eslint-enable */ 30247 30248 30249var ngOptionsDirective = ['$compile', '$document', '$parse', function($compile, $document, $parse) { 30250 30251 function parseOptionsExpression(optionsExp, selectElement, scope) { 30252 30253 var match = optionsExp.match(NG_OPTIONS_REGEXP); 30254 if (!(match)) { 30255 throw ngOptionsMinErr('iexp', 30256 'Expected expression in form of ' + 30257 '\'_select_ (as _label_)? for (_key_,)?_value_ in _collection_\'' + 30258 ' but got \'{0}\'. Element: {1}', 30259 optionsExp, startingTag(selectElement)); 30260 } 30261 30262 // Extract the parts from the ngOptions expression 30263 30264 // The variable name for the value of the item in the collection 30265 var valueName = match[5] || match[7]; 30266 // The variable name for the key of the item in the collection 30267 var keyName = match[6]; 30268 30269 // An expression that generates the viewValue for an option if there is a label expression 30270 var selectAs = / as /.test(match[0]) && match[1]; 30271 // An expression that is used to track the id of each object in the options collection 30272 var trackBy = match[9]; 30273 // An expression that generates the viewValue for an option if there is no label expression 30274 var valueFn = $parse(match[2] ? match[1] : valueName); 30275 var selectAsFn = selectAs && $parse(selectAs); 30276 var viewValueFn = selectAsFn || valueFn; 30277 var trackByFn = trackBy && $parse(trackBy); 30278 30279 // Get the value by which we are going to track the option 30280 // if we have a trackFn then use that (passing scope and locals) 30281 // otherwise just hash the given viewValue 30282 var getTrackByValueFn = trackBy ? 30283 function(value, locals) { return trackByFn(scope, locals); } : 30284 function getHashOfValue(value) { return hashKey(value); }; 30285 var getTrackByValue = function(value, key) { 30286 return getTrackByValueFn(value, getLocals(value, key)); 30287 }; 30288 30289 var displayFn = $parse(match[2] || match[1]); 30290 var groupByFn = $parse(match[3] || ''); 30291 var disableWhenFn = $parse(match[4] || ''); 30292 var valuesFn = $parse(match[8]); 30293 30294 var locals = {}; 30295 var getLocals = keyName ? function(value, key) { 30296 locals[keyName] = key; 30297 locals[valueName] = value; 30298 return locals; 30299 } : function(value) { 30300 locals[valueName] = value; 30301 return locals; 30302 }; 30303 30304 30305 function Option(selectValue, viewValue, label, group, disabled) { 30306 this.selectValue = selectValue; 30307 this.viewValue = viewValue; 30308 this.label = label; 30309 this.group = group; 30310 this.disabled = disabled; 30311 } 30312 30313 function getOptionValuesKeys(optionValues) { 30314 var optionValuesKeys; 30315 30316 if (!keyName && isArrayLike(optionValues)) { 30317 optionValuesKeys = optionValues; 30318 } else { 30319 // if object, extract keys, in enumeration order, unsorted 30320 optionValuesKeys = []; 30321 for (var itemKey in optionValues) { 30322 if (optionValues.hasOwnProperty(itemKey) && itemKey.charAt(0) !== '$') { 30323 optionValuesKeys.push(itemKey); 30324 } 30325 } 30326 } 30327 return optionValuesKeys; 30328 } 30329 30330 return { 30331 trackBy: trackBy, 30332 getTrackByValue: getTrackByValue, 30333 getWatchables: $parse(valuesFn, function(optionValues) { 30334 // Create a collection of things that we would like to watch (watchedArray) 30335 // so that they can all be watched using a single $watchCollection 30336 // that only runs the handler once if anything changes 30337 var watchedArray = []; 30338 optionValues = optionValues || []; 30339 30340 var optionValuesKeys = getOptionValuesKeys(optionValues); 30341 var optionValuesLength = optionValuesKeys.length; 30342 for (var index = 0; index < optionValuesLength; index++) { 30343 var key = (optionValues === optionValuesKeys) ? index : optionValuesKeys[index]; 30344 var value = optionValues[key]; 30345 30346 var locals = getLocals(value, key); 30347 var selectValue = getTrackByValueFn(value, locals); 30348 watchedArray.push(selectValue); 30349 30350 // Only need to watch the displayFn if there is a specific label expression 30351 if (match[2] || match[1]) { 30352 var label = displayFn(scope, locals); 30353 watchedArray.push(label); 30354 } 30355 30356 // Only need to watch the disableWhenFn if there is a specific disable expression 30357 if (match[4]) { 30358 var disableWhen = disableWhenFn(scope, locals); 30359 watchedArray.push(disableWhen); 30360 } 30361 } 30362 return watchedArray; 30363 }), 30364 30365 getOptions: function() { 30366 30367 var optionItems = []; 30368 var selectValueMap = {}; 30369 30370 // The option values were already computed in the `getWatchables` fn, 30371 // which must have been called to trigger `getOptions` 30372 var optionValues = valuesFn(scope) || []; 30373 var optionValuesKeys = getOptionValuesKeys(optionValues); 30374 var optionValuesLength = optionValuesKeys.length; 30375 30376 for (var index = 0; index < optionValuesLength; index++) { 30377 var key = (optionValues === optionValuesKeys) ? index : optionValuesKeys[index]; 30378 var value = optionValues[key]; 30379 var locals = getLocals(value, key); 30380 var viewValue = viewValueFn(scope, locals); 30381 var selectValue = getTrackByValueFn(viewValue, locals); 30382 var label = displayFn(scope, locals); 30383 var group = groupByFn(scope, locals); 30384 var disabled = disableWhenFn(scope, locals); 30385 var optionItem = new Option(selectValue, viewValue, label, group, disabled); 30386 30387 optionItems.push(optionItem); 30388 selectValueMap[selectValue] = optionItem; 30389 } 30390 30391 return { 30392 items: optionItems, 30393 selectValueMap: selectValueMap, 30394 getOptionFromViewValue: function(value) { 30395 return selectValueMap[getTrackByValue(value)]; 30396 }, 30397 getViewValueFromOption: function(option) { 30398 // If the viewValue could be an object that may be mutated by the application, 30399 // we need to make a copy and not return the reference to the value on the option. 30400 return trackBy ? copy(option.viewValue) : option.viewValue; 30401 } 30402 }; 30403 } 30404 }; 30405 } 30406 30407 30408 // Support: IE 9 only 30409 // We can't just jqLite('<option>') since jqLite is not smart enough 30410 // to create it in <select> and IE barfs otherwise. 30411 var optionTemplate = window.document.createElement('option'), 30412 optGroupTemplate = window.document.createElement('optgroup'); 30413 30414 function ngOptionsPostLink(scope, selectElement, attr, ctrls) { 30415 30416 var selectCtrl = ctrls[0]; 30417 var ngModelCtrl = ctrls[1]; 30418 var multiple = attr.multiple; 30419 30420 // The emptyOption allows the application developer to provide their own custom "empty" 30421 // option when the viewValue does not match any of the option values. 30422 for (var i = 0, children = selectElement.children(), ii = children.length; i < ii; i++) { 30423 if (children[i].value === '') { 30424 selectCtrl.hasEmptyOption = true; 30425 selectCtrl.emptyOption = children.eq(i); 30426 break; 30427 } 30428 } 30429 30430 // The empty option will be compiled and rendered before we first generate the options 30431 selectElement.empty(); 30432 30433 var providedEmptyOption = !!selectCtrl.emptyOption; 30434 30435 var unknownOption = jqLite(optionTemplate.cloneNode(false)); 30436 unknownOption.val('?'); 30437 30438 var options; 30439 var ngOptions = parseOptionsExpression(attr.ngOptions, selectElement, scope); 30440 // This stores the newly created options before they are appended to the select. 30441 // Since the contents are removed from the fragment when it is appended, 30442 // we only need to create it once. 30443 var listFragment = $document[0].createDocumentFragment(); 30444 30445 // Overwrite the implementation. ngOptions doesn't use hashes 30446 selectCtrl.generateUnknownOptionValue = function(val) { 30447 return '?'; 30448 }; 30449 30450 // Update the controller methods for multiple selectable options 30451 if (!multiple) { 30452 30453 selectCtrl.writeValue = function writeNgOptionsValue(value) { 30454 // The options might not be defined yet when ngModel tries to render 30455 if (!options) return; 30456 30457 var selectedOption = selectElement[0].options[selectElement[0].selectedIndex]; 30458 var option = options.getOptionFromViewValue(value); 30459 30460 // Make sure to remove the selected attribute from the previously selected option 30461 // Otherwise, screen readers might get confused 30462 if (selectedOption) selectedOption.removeAttribute('selected'); 30463 30464 if (option) { 30465 // Don't update the option when it is already selected. 30466 // For example, the browser will select the first option by default. In that case, 30467 // most properties are set automatically - except the `selected` attribute, which we 30468 // set always 30469 30470 if (selectElement[0].value !== option.selectValue) { 30471 selectCtrl.removeUnknownOption(); 30472 30473 selectElement[0].value = option.selectValue; 30474 option.element.selected = true; 30475 } 30476 30477 option.element.setAttribute('selected', 'selected'); 30478 } else { 30479 selectCtrl.selectUnknownOrEmptyOption(value); 30480 } 30481 }; 30482 30483 selectCtrl.readValue = function readNgOptionsValue() { 30484 30485 var selectedOption = options.selectValueMap[selectElement.val()]; 30486 30487 if (selectedOption && !selectedOption.disabled) { 30488 selectCtrl.unselectEmptyOption(); 30489 selectCtrl.removeUnknownOption(); 30490 return options.getViewValueFromOption(selectedOption); 30491 } 30492 return null; 30493 }; 30494 30495 // If we are using `track by` then we must watch the tracked value on the model 30496 // since ngModel only watches for object identity change 30497 // FIXME: When a user selects an option, this watch will fire needlessly 30498 if (ngOptions.trackBy) { 30499 scope.$watch( 30500 function() { return ngOptions.getTrackByValue(ngModelCtrl.$viewValue); }, 30501 function() { ngModelCtrl.$render(); } 30502 ); 30503 } 30504 30505 } else { 30506 30507 selectCtrl.writeValue = function writeNgOptionsMultiple(values) { 30508 // The options might not be defined yet when ngModel tries to render 30509 if (!options) return; 30510 30511 // Only set `<option>.selected` if necessary, in order to prevent some browsers from 30512 // scrolling to `<option>` elements that are outside the `<select>` element's viewport. 30513 var selectedOptions = values && values.map(getAndUpdateSelectedOption) || []; 30514 30515 options.items.forEach(function(option) { 30516 if (option.element.selected && !includes(selectedOptions, option)) { 30517 option.element.selected = false; 30518 } 30519 }); 30520 }; 30521 30522 30523 selectCtrl.readValue = function readNgOptionsMultiple() { 30524 var selectedValues = selectElement.val() || [], 30525 selections = []; 30526 30527 forEach(selectedValues, function(value) { 30528 var option = options.selectValueMap[value]; 30529 if (option && !option.disabled) selections.push(options.getViewValueFromOption(option)); 30530 }); 30531 30532 return selections; 30533 }; 30534 30535 // If we are using `track by` then we must watch these tracked values on the model 30536 // since ngModel only watches for object identity change 30537 if (ngOptions.trackBy) { 30538 30539 scope.$watchCollection(function() { 30540 if (isArray(ngModelCtrl.$viewValue)) { 30541 return ngModelCtrl.$viewValue.map(function(value) { 30542 return ngOptions.getTrackByValue(value); 30543 }); 30544 } 30545 }, function() { 30546 ngModelCtrl.$render(); 30547 }); 30548 30549 } 30550 } 30551 30552 if (providedEmptyOption) { 30553 30554 // compile the element since there might be bindings in it 30555 $compile(selectCtrl.emptyOption)(scope); 30556 30557 selectElement.prepend(selectCtrl.emptyOption); 30558 30559 if (selectCtrl.emptyOption[0].nodeType === NODE_TYPE_COMMENT) { 30560 // This means the empty option has currently no actual DOM node, probably because 30561 // it has been modified by a transclusion directive. 30562 selectCtrl.hasEmptyOption = false; 30563 30564 // Redefine the registerOption function, which will catch 30565 // options that are added by ngIf etc. (rendering of the node is async because of 30566 // lazy transclusion) 30567 selectCtrl.registerOption = function(optionScope, optionEl) { 30568 if (optionEl.val() === '') { 30569 selectCtrl.hasEmptyOption = true; 30570 selectCtrl.emptyOption = optionEl; 30571 selectCtrl.emptyOption.removeClass('ng-scope'); 30572 // This ensures the new empty option is selected if previously no option was selected 30573 ngModelCtrl.$render(); 30574 30575 optionEl.on('$destroy', function() { 30576 var needsRerender = selectCtrl.$isEmptyOptionSelected(); 30577 30578 selectCtrl.hasEmptyOption = false; 30579 selectCtrl.emptyOption = undefined; 30580 30581 if (needsRerender) ngModelCtrl.$render(); 30582 }); 30583 } 30584 }; 30585 30586 } else { 30587 // remove the class, which is added automatically because we recompile the element and it 30588 // becomes the compilation root 30589 selectCtrl.emptyOption.removeClass('ng-scope'); 30590 } 30591 30592 } 30593 30594 // We will re-render the option elements if the option values or labels change 30595 scope.$watchCollection(ngOptions.getWatchables, updateOptions); 30596 30597 // ------------------------------------------------------------------ // 30598 30599 function addOptionElement(option, parent) { 30600 var optionElement = optionTemplate.cloneNode(false); 30601 parent.appendChild(optionElement); 30602 updateOptionElement(option, optionElement); 30603 } 30604 30605 function getAndUpdateSelectedOption(viewValue) { 30606 var option = options.getOptionFromViewValue(viewValue); 30607 var element = option && option.element; 30608 30609 if (element && !element.selected) element.selected = true; 30610 30611 return option; 30612 } 30613 30614 function updateOptionElement(option, element) { 30615 option.element = element; 30616 element.disabled = option.disabled; 30617 // Support: IE 11 only, Edge 12-13 only 30618 // NOTE: The label must be set before the value, otherwise IE 11 & Edge create unresponsive 30619 // selects in certain circumstances when multiple selects are next to each other and display 30620 // the option list in listbox style, i.e. the select is [multiple], or specifies a [size]. 30621 // See https://github.com/angular/angular.js/issues/11314 for more info. 30622 // This is unfortunately untestable with unit / e2e tests 30623 if (option.label !== element.label) { 30624 element.label = option.label; 30625 element.textContent = option.label; 30626 } 30627 element.value = option.selectValue; 30628 } 30629 30630 function updateOptions() { 30631 var previousValue = options && selectCtrl.readValue(); 30632 30633 // We must remove all current options, but cannot simply set innerHTML = null 30634 // since the providedEmptyOption might have an ngIf on it that inserts comments which we 30635 // must preserve. 30636 // Instead, iterate over the current option elements and remove them or their optgroup 30637 // parents 30638 if (options) { 30639 30640 for (var i = options.items.length - 1; i >= 0; i--) { 30641 var option = options.items[i]; 30642 if (isDefined(option.group)) { 30643 jqLiteRemove(option.element.parentNode); 30644 } else { 30645 jqLiteRemove(option.element); 30646 } 30647 } 30648 } 30649 30650 options = ngOptions.getOptions(); 30651 30652 var groupElementMap = {}; 30653 30654 options.items.forEach(function addOption(option) { 30655 var groupElement; 30656 30657 if (isDefined(option.group)) { 30658 30659 // This option is to live in a group 30660 // See if we have already created this group 30661 groupElement = groupElementMap[option.group]; 30662 30663 if (!groupElement) { 30664 30665 groupElement = optGroupTemplate.cloneNode(false); 30666 listFragment.appendChild(groupElement); 30667 30668 // Update the label on the group element 30669 // "null" is special cased because of Safari 30670 groupElement.label = option.group === null ? 'null' : option.group; 30671 30672 // Store it for use later 30673 groupElementMap[option.group] = groupElement; 30674 } 30675 30676 addOptionElement(option, groupElement); 30677 30678 } else { 30679 30680 // This option is not in a group 30681 addOptionElement(option, listFragment); 30682 } 30683 }); 30684 30685 selectElement[0].appendChild(listFragment); 30686 30687 ngModelCtrl.$render(); 30688 30689 // Check to see if the value has changed due to the update to the options 30690 if (!ngModelCtrl.$isEmpty(previousValue)) { 30691 var nextValue = selectCtrl.readValue(); 30692 var isNotPrimitive = ngOptions.trackBy || multiple; 30693 if (isNotPrimitive ? !equals(previousValue, nextValue) : previousValue !== nextValue) { 30694 ngModelCtrl.$setViewValue(nextValue); 30695 ngModelCtrl.$render(); 30696 } 30697 } 30698 } 30699 } 30700 30701 return { 30702 restrict: 'A', 30703 terminal: true, 30704 require: ['select', 'ngModel'], 30705 link: { 30706 pre: function ngOptionsPreLink(scope, selectElement, attr, ctrls) { 30707 // Deactivate the SelectController.register method to prevent 30708 // option directives from accidentally registering themselves 30709 // (and unwanted $destroy handlers etc.) 30710 ctrls[0].registerOption = noop; 30711 }, 30712 post: ngOptionsPostLink 30713 } 30714 }; 30715}]; 30716 30717/** 30718 * @ngdoc directive 30719 * @name ngPluralize 30720 * @restrict EA 30721 * 30722 * @description 30723 * `ngPluralize` is a directive that displays messages according to en-US localization rules. 30724 * These rules are bundled with angular.js, but can be overridden 30725 * (see {@link guide/i18n Angular
30725 i18n} dev guide). You configure ngPluralize directive 30726 * by specifying the mappings between 30727 * [plural categories](http://unicode.org/repos/cldr-tmp/trunk/diff/supplemental/language_plural_rules.html) 30728 * and the strings to be displayed. 30729 * 30730 * # Plural categories and explicit number rules 30731 * There are two 30732 * [plural categories](http://unicode.org/repos/cldr-tmp/trunk/diff/supplemental/language_plural_rules.html) 30733 * in Angular's default en-US locale: "one" and "other". 30734 * 30735 * While a plural category may match many numbers (for example, in en-US locale, "other" can match 30736 * any number that is not 1), an explicit number rule can only match one number. For example, the 30737 * explicit number rule for "3" matches the number 3. There are examples of plural categories 30738 * and explicit number rules throughout the rest of this documentation. 30739 * 30740 * # Configuring ngPluralize 30741 * You configure ngPluralize by providing 2 attributes: `count` and `when`. 30742 * You can also provide an optional attribute, `offset`. 30743 * 30744 * The value of the `count` attribute can be either a string or an {@link guide/expression 30745 * Angular expression}; these are evaluated on the current scope for its bound value. 30746 * 30747 * The `when` attribute specifies the mappings between plural categories and the actual 30748 * string to be displayed. The value of the attribute should be a JSON object. 30749 * 30750 * The following example shows how to configure ngPluralize: 30751 * 30752 * ```html 30753 * <ng-pluralize count="personCount" 30754 when="{'0': 'Nobody is viewing.', 30755 * 'one': '1 person is viewing.', 30756 * 'other': '{} people are viewing.'}"> 30757 * </ng-pluralize> 30758 *``` 30759 * 30760 * In the example, `"0: Nobody is viewing."` is an explicit number rule. If you did not 30761 * specify this rule, 0 would be matched to the "other" category and "0 people are viewing" 30762 * would be shown instead of "Nobody is viewing". You can specify an explicit number rule for 30763 * other numbers, for example 12, so that instead of showing "12 people are viewing", you can 30764 * show "a dozen people are viewing". 30765 * 30766 * You can use a set of closed braces (`{}`) as a placeholder for the number that you want substituted 30767 * into pluralized strings. In the previous example, Angular will replace `{}` with 30768 * <span ng-non-bindable>`{{personCount}}
30768`</span>. The closed braces `{}` is a placeholder 30769 * for <span ng-non-bindable>{{numberExpression}}</span>. 30770 * 30771 * If no rule is defined for a category, then an empty string is displayed and a warning is generated. 30772 * Note that some locales define more categories than `one` and `other`. For example, fr-fr defines `few` and `many`. 30773 * 30774 * # Configuring ngPluralize with offset 30775 * The `offset` attribute allows further customization of pluralized text, which can result in 30776 * a better user experience. For example, instead of the message "4 people are viewing this document", 30777 * you might display "John, Kate and 2 others are viewing this document". 30778 * The offset attribute allows you to offset a number by any desired value. 30779 * Let's take a look at an example: 30780 * 30781 * ```html 30782 * <ng-pluralize count="personCount" offset=2 30783 * when="{'0': 'Nobody is viewing.', 30784 * '1': '{{person1}} is viewing.', 30785 * '2': '{{person1}} and {{person2}} are viewing.', 30786 * 'one': '{{person1}}, {{person2}} and one other person are viewing.', 30787 * 'other': '{{person1}}, {{person2}} and {} other people are viewing.'}"> 30788 * </ng-pluralize> 30789 * ``` 30790 * 30791 * Notice that we are still using two plural categories(one, other), but we added 30792 * three explicit number rules 0, 1 and 2. 30793 * When one person, perhaps John, views the document, "John is viewing" will be shown. 30794 * When three people view the document, no explicit number rule is found, so 30795 * an offset of 2 is taken off 3, and Angular
vendor: 6,786 bytes, lines 30795-30956
30795 uses 1 to decide the plural category. 30796 * In this case, plural category 'one' is matched and "John, Mary and one other person are viewing" 30797 * is shown. 30798 * 30799 * Note that when you specify offsets, you must provide explicit number rules for 30800 * numbers from 0 up to and including the offset. If you use an offset of 3, for example, 30801 * you must provide explicit number rules for 0, 1, 2 and 3. You must also provide plural strings for 30802 * plural categories "one" and "other". 30803 * 30804 * @param {string|expression} count The variable to be bound to. 30805 * @param {string} when The mapping between plural category to its corresponding strings. 30806 * @param {number=} offset Offset to deduct from the total number. 30807 * 30808 * @example 30809 <example module="pluralizeExample" name="ng-pluralize"> 30810 <file name="index.html"> 30811 <script> 30812 angular.module('pluralizeExample', []) 30813 .controller('ExampleController', ['$scope', function($scope) { 30814 $scope.person1 = 'Igor'; 30815 $scope.person2 = 'Misko'; 30816 $scope.personCount = 1; 30817 }]); 30818 </script> 30819 <div ng-controller="ExampleController"> 30820 <label>Person 1:<input type="text" ng-model="person1" value="Igor" /></label><br/> 30821 <label>Person 2:<input type="text" ng-model="person2" value="Misko" /></label><br/> 30822 <label>Number of People:<input type="text" ng-model="personCount" value="1" /></label><br/> 30823 30824 <!--- Example with simple pluralization rules for en locale ---> 30825 Without Offset: 30826 <ng-pluralize count="personCount" 30827 when="{'0': 'Nobody is viewing.', 30828 'one': '1 person is viewing.', 30829 'other': '{} people are viewing.'}"> 30830 </ng-pluralize><br> 30831 30832 <!--- Example with offset ---> 30833 With Offset(2): 30834 <ng-pluralize count="personCount" offset=2 30835 when="{'0': 'Nobody is viewing.', 30836 '1': '{{person1}} is viewing.', 30837 '2': '{{person1}} and {{person2}} are viewing.', 30838 'one': '{{person1}}, {{person2}} and one other person are viewing.', 30839 'other': '{{person1}}, {{person2}} and {} other people are viewing.'}"> 30840 </ng-pluralize> 30841 </div> 30842 </file> 30843 <file name="protractor.js" type="protractor"> 30844 it('should show correct pluralized string', function() { 30845 var withoutOffset = element.all(by.css('ng-pluralize')).get(0); 30846 var withOffset = element.all(by.css('ng-pluralize')).get(1); 30847 var countInput = element(by.model('personCount')); 30848 30849 expect(withoutOffset.getText()).toEqual('1 person is viewing.'); 30850 expect(withOffset.getText()).toEqual('Igor is viewing.'); 30851 30852 countInput.clear(); 30853 countInput.sendKeys('0'); 30854 30855 expect(withoutOffset.getText()).toEqual('Nobody is viewing.'); 30856 expect(withOffset.getText()).toEqual('Nobody is viewing.'); 30857 30858 countInput.clear(); 30859 countInput.sendKeys('2'); 30860 30861 expect(withoutOffset.getText()).toEqual('2 people are viewing.'); 30862 expect(withOffset.getText()).toEqual('Igor and Misko are viewing.'); 30863 30864 countInput.clear(); 30865 countInput.sendKeys('3'); 30866 30867 expect(withoutOffset.getText()).toEqual('3 people are viewing.'); 30868 expect(withOffset.getText()).toEqual('Igor, Misko and one other person are viewing.'); 30869 30870 countInput.clear(); 30871 countInput.sendKeys('4'); 30872 30873 expect(withoutOffset.getText()).toEqual('4 people are viewing.'); 30874 expect(withOffset.getText()).toEqual('Igor, Misko and 2 other people are viewing.'); 30875 }); 30876 it('should show data-bound names', function() { 30877 var withOffset = element.all(by.css('ng-pluralize')).get(1); 30878 var personCount = element(by.model('personCount')); 30879 var person1 = element(by.model('person1')); 30880 var person2 = element(by.model('person2')); 30881 personCount.clear(); 30882 personCount.sendKeys('4'); 30883 person1.clear(); 30884 person1.sendKeys('Di'); 30885 person2.clear(); 30886 person2.sendKeys('Vojta'); 30887 expect(withOffset.getText()).toEqual('Di, Vojta and 2 other people are viewing.'); 30888 }); 30889 </file> 30890 </example> 30891 */ 30892var ngPluralizeDirective = ['$locale', '$interpolate', '$log', function($locale, $interpolate, $log) { 30893 var BRACE = /{}/g, 30894 IS_WHEN = /^when(Minus)?(.+)$/; 30895 30896 return { 30897 link: function(scope, element, attr) { 30898 var numberExp = attr.count, 30899 whenExp = attr.$attr.when && element.attr(attr.$attr.when), // we have {{}} in attrs 30900 offset = attr.offset || 0, 30901 whens = scope.$eval(whenExp) || {}, 30902 whensExpFns = {}, 30903 startSymbol = $interpolate.startSymbol(), 30904 endSymbol = $interpolate.endSymbol(), 30905 braceReplacement = startSymbol + numberExp + '-' + offset + endSymbol, 30906 watchRemover = angular.noop, 30907 lastCount; 30908 30909 forEach(attr, function(expression, attributeName) { 30910 var tmpMatch = IS_WHEN.exec(attributeName); 30911 if (tmpMatch) { 30912 var whenKey = (tmpMatch[1] ? '-' : '') + lowercase(tmpMatch[2]); 30913 whens[whenKey] = element.attr(attr.$attr[attributeName]); 30914 } 30915 }); 30916 forEach(whens, function(expression, key) { 30917 whensExpFns[key] = $interpolate(expression.replace(BRACE, braceReplacement)); 30918 30919 }); 30920 30921 scope.$watch(numberExp, function ngPluralizeWatchAction(newVal) { 30922 var count = parseFloat(newVal); 30923 var countIsNaN = isNumberNaN(count); 30924 30925 if (!countIsNaN && !(count in whens)) { 30926 // If an explicit number rule such as 1, 2, 3... is defined, just use it. 30927 // Otherwise, check it against pluralization rules in $locale service. 30928 count = $locale.pluralCat(count - offset); 30929 } 30930 30931 // If both `count` and `lastCount` are NaN, we don't need to re-register a watch. 30932 // In JS `NaN !== NaN`, so we have to explicitly check. 30933 if ((count !== lastCount) && !(countIsNaN && isNumberNaN(lastCount))) { 30934 watchRemover(); 30935 var whenExpFn = whensExpFns[count]; 30936 if (isUndefined(whenExpFn)) { 30937 if (newVal != null) { 30938 $log.debug('ngPluralize: no rule defined for \'' + count + '\' in ' + whenExp); 30939 } 30940 watchRemover = noop; 30941 updateElementText(); 30942 } else { 30943 watchRemover = scope.$watch(whenExpFn, updateElementText); 30944 } 30945 lastCount = count; 30946 } 30947 }); 30948 30949 function updateElementText(newText) { 30950 element.text(newText || ''); 30951 } 30952 } 30953 }; 30954}]; 30955 30956/*
30956 exported ngRepeatDirective */ 30957 30958/** 30959 * @ngdoc directive 30960 * @name ngRepeat 30961 * @multiElement 30962 * @restrict A 30963 * 30964 * @description 30965 * The `ngRepeat` directive instantiates a template once per item from a collection. Each template 30966 * instance gets its own scope, where the given loop variable is set to the current collection item, 30967 * and `$index` is set to the item index or key. 30968 * 30969 * Special properties are exposed on the local scope of each template instance, including: 30970 * 30971 * | Variable | Type | Details | 30972 * |-----------|-----------------|-----------------------------------------------------------------------------| 30973 * | `$index` | {@type number} | iterator offset of the repeated element (0..length-1) | 30974 * | `$first` | {@type boolean} | true if the repeated element is first in the iterator. | 30975 * | `$middle` | {@type boolean} | true if the repeated element is between the first and last in the iterator. | 30976 * | `$last` | {@type boolean} | true if the repeated element is last in the iterator. | 30977 * | `$even` | {@type boolean} | true if the iterator position `$index` is even (otherwise false). | 30978 * | `$odd` | {@type boolean} | true if the iterator position `$index` is odd (otherwise false). | 30979 * 30980 * <div class="alert alert-info"> 30981 * Creating aliases for these properties is possible with {@link ng.directive:ngInit `ngInit`}. 30982 * This may be useful when, for instance, nesting ngRepeats. 30983 * </div> 30984 * 30985 * 30986 * # Iterating over object properties 30987 * 30988 * It is possible to get `ngRepeat` to iterate over the properties of an object using the following 30989 * syntax: 30990 * 30991 * ```js 30992 * <div ng-repeat="(key, value) in myObj"> ... </div> 30993 * ``` 30994 * 30995 * However, there are a few limitations compared to array iteration: 30996 * 30997 * - The JavaScript specification does not define the order of keys 30998 * returned for an object, so Angular relies on the order returned by the browser 30999 * when running `for key in myObj`. Browsers generally follow the strategy of providing 31000 * keys in the order in which they were defined, although there are exceptions when keys are deleted 31001 * and reinstated. See the 31002 * [MDN page on `delete` for more info](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/delete#Cross-browser_notes). 31003 * 31004 * - `ngRepeat` will silently *ignore* object keys starting with `$`, because 31005 * it's a prefix used by Angular for public (`$`) and private (`$$`) properties. 31006 * 31007 * - The built-in filters {@link ng.orderBy orderBy} and {@link ng.filter filter} do not work with 31008 * objects, and will throw an error if used with one. 31009 * 31010 * If you are hitting any of these limitations, the recommended workaround is to convert your object into an array 31011 * that is sorted into the order that you prefer before providing it to `ngRepeat`. You could 31012 * do this with a filter such as [toArrayFilter](http://ngmodules.org/modules/angular-toArrayFilter) 31013 * or implement a `$watch` on the object yourself. 31014 * 31015 * 31016 * # Tracking and Duplicates 31017 * 31018 * `ngRepeat` uses {@link $rootScope.Scope#$watchCollection $watchCollection} to detect changes in 31019 * the collection. When a change happens, `ngRepeat` then makes the corresponding changes to the DOM: 31020 * 31021 * * When an item is added, a new instance of the template is added to the DOM. 31022 * * When an item is removed, its template instance is removed from the DOM. 31023 * * When items are reordered, their respective templates are reordered in the DOM. 31024 * 31025 * To minimize creation of DOM elements, `ngRepeat` uses a function 31026 * to "keep track" of all items in the collection and their corresponding DOM elements. 31027 * For example, if an item is added to the collection, `ngRepeat` will know that all other items 31028 * already have DOM elements, and will not re-render them. 31029 * 31030 * The default tracking function (which tracks items by their identity) does not allow 31031 * duplicate items in arrays. This is because when there are duplicates, it is not possible 31032 * to maintain a one-to-one mapping between collection items and DOM elements. 31033 * 31034 * If you do need to repeat duplicate items, you can substitute the default tracking behavior 31035 * with your own using the `track by` expression. 31036 * 31037 * For example, you may track items by the index of each item in the collection, using the 31038 * special scope property `$index`: 31039 * ```html 31040 * <div ng-repeat="n in [42, 42, 43, 43] track by $index"> 31041 * {{n}} 31042 * </div> 31043 * ``` 31044 * 31045 * You may also use arbitrary expressions in `track by`, including references to custom functions 31046 * on the scope: 31047 * ```html 31048 * <div ng-repeat="n in [42, 42, 43, 43] track by myTrackingFunction(n)"> 31049 * {{n}} 31050 * </div> 31051 * ``` 31052 * 31053 * <div class="alert alert-success"> 31054 * If you are working with objects that have a unique identifier property, you should track 31055 * by this identifier instead of the object instance. Should you reload your data later, `ngRepeat` 31056 * will not have to rebuild the DOM elements for items it has already rendered, even if the 31057 * JavaScript objects in the collection have been substituted for new ones. For large collections, 31058 * this significantly improves rendering performance. If you don't have a unique identifier, 31059 * `track by $index` can also provide a performance boost. 31060 * </div> 31061 * 31062 * ```html 31063 * <div ng-repeat="model in collection track by model.id"> 31064 * {{model.name}} 31065 * </div> 31066 * ``` 31067 * 31068 * <br /> 31069 * <div class="alert alert-warning"> 31070 * Avoid using `track by $index` when the repeated template contains 31071 * {@link guide/expression#one-time-binding one-time bindings}. In such cases, the `nth` DOM 31072 * element will always be matched with the `nth` item of the array, so the bindings on that element 31073 * will not be updated even when the corresponding item changes, essentially causing the view to get 31074 * out-of-sync with the underlying data. 31075 * </div> 31076 * 31077 * When no `track by` expression is provided, it is equivalent to tracking by the built-in 31078 * `$id` function, which tracks items by their identity: 31079 * ```html 31080 * <div ng-repeat="obj in collection track by $id(obj)"> 31081 * {{obj.prop}} 31082 * </div> 31083 * ``` 31084 * 31085 * <br /> 31086 * <div class="alert alert-warning"> 31087 * **Note:** `track by` must always be the last expression: 31088 * </div> 31089 * ``` 31090 * <div ng-repeat="model in collection | orderBy: 'id' as filtered_result track by model.id"> 31091 * {{model.name}} 31092 * </div> 31093 * ``` 31094 * 31095 * 31096 * # Special repeat start and end points 31097 * To repeat a series of elements instead of just one parent element, ngRepeat (as well as other ng directives) supports extending 31098 * the range of the repeater by defining explicit start and end points by using **ng-repeat-start** and **ng-repeat-end** respectively. 31099 * 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) 31100 * up to and including the ending HTML tag where **ng-repeat-end** is placed. 31101 * 31102 * The example below makes use of this feature: 31103 * ```html 31104 * <header ng-repeat-start="item in items"> 31105 * Header {{ item }} 31106 * </header> 31107 * <div class="body"> 31108 * Body {{ item }} 31109 * </div> 31110 * <footer ng-repeat-end> 31111 * Footer {{ item }} 31112 * </footer> 31113 * ``` 31114 * 31115 * And with an input of {@type ['A','B']} for the items variable in the example above, the output will evaluate to: 31116 * ```html 31117 * <header> 31118 * Header A 31119 * </header> 31120 * <div class="body"> 31121 * Body A 31122 * </div> 31123 * <footer> 31124 * Footer A 31125 * </footer> 31126 * <header> 31127 * Header B 31128 * </header> 31129 * <div class="body"> 31130 * Body B 31131 * </div> 31132 * <footer> 31133 * Footer B 31134 * </footer> 31135 * ``` 31136 * 31137 * The custom start and end points for ngRepeat also support all other HTML directive syntax flavors provided in AngularJS (such 31138 * as **data-ng-repeat-start**, **x-ng-repeat-start** and **ng:repeat-start**). 31139 * 31140 * @animations 31141 * | Animation | Occurs | 31142 * |----------------------------------|-------------------------------------| 31143 * | {@link ng.$animate#enter enter} | when a new item is added to the list or when an item is revealed after a filter | 31144 * | {@link ng.$animate#leave leave} | when an item is removed from the list or when an item is filtered out | 31145 * | {@link ng.$animate#move move } | when an adjacent item is filtered out causing a reorder or when the item contents are reordered | 31146 *
31147 * See the example below for defining CSS animations with ngRepeat. 31148 * 31149 * @element ANY 31150 * @scope 31151 * @priority 1000 31152 * @param {repeat_expression} ngRepeat The expression indicating how to enumerate a collection. These 31153 * formats are currently supported: 31154 * 31155 * * `variable in expression` – where variable is the user defined loop variable and `expression` 31156 * is a scope expression giving the collection to enumerate. 31157 * 31158 * For example: `album in artist.albums`. 31159 * 31160 * * `(key, value) in expression` – where `key` and `value` can be any user defined identifiers, 31161 * and `expression` is the scope expression giving the collection to enumerate. 31162 * 31163 * For example: `(name, age) in {'adam':10, 'amalie':12}`. 31164 * 31165 * * `variable in expression track by tracking_expression` – You can also provide an optional tracking expression 31166 * which can be used to associate the objects in the collection with the DOM elements. If no tracking expression 31167 * is specified, ng-repeat associates elements by identity. It is an error to have 31168 * more than one tracking expression value resolve to the same key. (This would mean that two distinct objects are 31169 * mapped to the same DOM element, which is not possible.) 31170 * 31171 * <div class="alert alert-warning"> 31172 * <strong>Note:</strong> the `track by` expression must come last - after any filters, and the alias expression. 31173 * </div> 31174 * 31175 * For example: `item in items` is equivalent to `item in items track by $id(item)`. This implies that the DOM elements 31176 * will be associated by item identity in the array. 31177 * 31178 * For example: `item in items track by $id(item)`. A built in `$id()` function can be used to assign a unique 31179 * `$$hashKey` property to each item in the array. This property is then used as a key to associated DOM elements 31180 * with the corresponding item in the array by identity. Moving the same object in array would move the DOM 31181 * element in the same way in the DOM. 31182 * 31183 * For example: `item in items track by item.id` is a typical pattern when the items come from the database. In this 31184 * case the object identity does not matter. Two objects are considered equivalent as long as their `id` 31185 * property is same. 31186 * 31187 * For example: `item in items | filter:searchText track by item.id` is a pattern that might be used to apply a filter 31188 * to items in conjunction with a tracking expression. 31189 * 31190 * * `variable in expression as alias_expression` – You can also provide an optional alias expression which will then store the 31191 * intermediate results of the repeater after the filters have been applied. Typically this is used to render a special message 31192 * when a filter is active on the repeater, but the filtered result set is empty. 31193 * 31194 * For example: `item in items | filter:x as results` will store the fragment of the repeated items as `results`, but only after 31195 * the items have been processed through the filter. 31196 * 31197 * Please note that `as [variable name] is not an operator but rather a part of ngRepeat micro-syntax so it can be used only at the end 31198 * (and not as operator, inside an expression). 31199 * 31200 * For example: `item in items | filter : x | orderBy : order | limitTo : limit as results` . 31201 * 31202 * @example 31203 * This example uses `ngRepeat` to display a list of people. A filter is used to restrict the displayed 31204 * results by name or by age. New (entering) and removed (leaving) items are animated. 31205 <example module="ngRepeat" name="ngRepeat" deps="angular-animate.js" animations="true" name="ng-repeat"> 31206 <file name="index.html"> 31207 <div ng-controller="repeatController"> 31208 I have {{friends.length}} friends. They are: 31209 <input type="search" ng-model="q" placeholder="filter friends..." aria-label="filter friends" /> 31210 <ul class="example-animate-container"> 31211 <li class="animate-repeat" ng-repeat="friend in friends | filter:q as results"> 31212 [{{$index + 1}}] {{friend.name}} who is {{friend.age}} years old. 31213 </li> 31214 <li class="animate-repeat" ng-if="results.length === 0"> 31215 <strong>No results found...</strong> 31216 </li> 31217 </ul> 31218 </div> 31219 </file> 31220 <file name="script.js"> 31221 angular.module('ngRepeat', ['ngAnimate']).controller('repeatController', function($scope) { 31222 $scope.friends = [ 31223 {name:'John', age:25, gender:'boy'}, 31224 {name:'Jessie', age:30, gender:'girl'}, 31225 {name:'Johanna', age:28, gender:'girl'}, 31226 {name:'Joy', age:15, gender:'girl'}, 31227 {name:'Mary', age:28, gender:'girl'}, 31228 {name:'Peter', age:95, gender:'boy'}, 31229 {name:'Sebastian', age:50, gender:'boy'}, 31230 {name:'Erika', age:27, gender:'girl'}, 31231 {name:'Patrick', age:40, gender:'boy'}, 31232 {name:'Samantha', age:60, gender:'girl'} 31233 ]; 31234 }); 31235 </file> 31236 <file name="animations.css"> 31237 .example-animate-container { 31238 background:white; 31239 border:1px solid black; 31240 list-style:none; 31241 margin:0; 31242 padding:0 10px; 31243 } 31244 31245 .animate-repeat { 31246 line-height:30px; 31247 list-style:none; 31248 box-sizing:border-box; 31249 } 31250 31251 .animate-repeat.ng-move, 31252 .animate-repeat.ng-enter, 31253 .animate-repeat.ng-leave { 31254 transition:all linear 0.5s; 31255 } 31256 31257 .animate-repeat.ng-leave.ng-leave-active, 31258 .animate-repeat.ng-move, 31259 .animate-repeat.ng-enter { 31260 opacity:0; 31261 max-height:0; 31262 } 31263 31264 .animate-repeat.ng-leave,
31265 .animate-repeat.ng-move.ng-move-active, 31266 .animate-repeat.ng-enter.ng-enter-active { 31267 opacity:1; 31268 max-height:30px; 31269 } 31270 </file> 31271 <file name="protractor.js" type="protractor"> 31272 var friends = element.all(by.repeater('friend in friends')); 31273 31274 it('should render initial data set', function() { 31275 expect(friends.count()).toBe(10); 31276 expect(friends.get(0).getText()).toEqual('[1] John who is 25 years old.'); 31277 expect(friends.get(1).getText()).toEqual('[2] Jessie who is 30 years old.'); 31278 expect(friends.last().getText()).toEqual('[10] Samantha who is 60 years old.'); 31279 expect(element(by.binding('friends.length')).getText()) 31280 .toMatch("I have 10 friends. They are:"); 31281 }); 31282 31283 it('should update repeater when filter predicate changes', function() { 31284 expect(friends.count()).toBe(10); 31285 31286 element(by.model('q')).sendKeys('ma'); 31287 31288 expect(friends.count()).toBe(2); 31289 expect(friends.get(0).getText()).toEqual('[1] Mary who is 28 years old.'); 31290 expect(friends.last().getText()).toEqual('[2] Samantha who is 60 years old.'); 31291 }); 31292 </file> 31293 </example> 31294 */ 31295var ngRepeatDirective = ['$parse', '$animate', '$compile', function($parse, $animate, $compile) { 31296 var NG_REMOVED = '$$NG_REMOVED'; 31297 var ngRepeatMinErr = minErr('ngRepeat'); 31298 31299 var updateScope = function(scope, index, valueIdentifier, value, keyIdentifier, key, arrayLength) { 31300 // TODO(perf): generate setters to shave off ~40ms or 1-1.5% 31301 scope[valueIdentifier] = value; 31302 if (keyIdentifier) scope[keyIdentifier] = key; 31303 scope.$index = index; 31304 scope.$first = (index === 0); 31305 scope.$last = (index === (arrayLength - 1)); 31306 scope.$middle = !(scope.$first || scope.$last); 31307 // eslint-disable-next-line no-bitwise 31308 scope.$odd = !(scope.$even = (index & 1) === 0); 31309 }; 31310 31311 var getBlockStart = function(block) { 31312 return block.clone[0]; 31313 }; 31314 31315 var getBlockEnd = function(block) { 31316 return block.clone[block.clone.length - 1]; 31317 }; 31318 31319 31320 return { 31321 restrict: 'A', 31322 multiElement: true, 31323 transclude: 'element', 31324 priority: 1000, 31325 terminal: true, 31326 $$tlb: true, 31327 compile: function ngRepeatCompile($element, $attr) { 31328 var expression = $attr.ngRepeat; 31329 var ngRepeatEndComment = $compile.$$createComment('end ngRepeat', expression); 31330 31331 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*$/); 31332 31333 if (!match) { 31334 throw ngRepeatMinErr('iexp', 'Expected expression in form of \'_item_ in _collection_[ track by _id_]\' but got \'{0}\'.', 31335 expression); 31336 } 31337 31338 var lhs = match[1]; 31339 var rhs = match[2]; 31340 var aliasAs = match[3]; 31341 var trackByExp = match[4]; 31342 31343 match = lhs.match(/^(?:(\s*[$\w]+)|\(\s*([$\w]+)\s*,\s*([$\w]+)\s*\))$/); 31344 31345 if (!match) { 31346 throw ngRepeatMinErr('iidexp', '\'_item_\' in \'_item_ in _collection_\' should be an identifier or \'(_key_, _value_)\' expression, but got \'{0}\'.', 31347 lhs); 31348 } 31349 var valueIdentifier = match[3] || match[1]; 31350 var keyIdentifier = match[2]; 31351 31352 if (aliasAs && (!/^[$a-zA-Z_][$a-zA-Z0-9_]*$/.test(aliasAs) || 31353 /^(null|undefined|this|\$index|\$first|\$middle|\$last|\$even|\$odd|\$parent|\$root|\$id)$/.test(aliasAs))) { 31354 throw ngRepeatMinErr('badident', 'alias \'{0}\' is invalid --- must be a valid JS identifier which is not a reserved name.', 31355 aliasAs); 31356 } 31357 31358 var trackByExpGetter, trackByIdExpFn, trackByIdArrayFn, trackByIdObjFn; 31359 var hashFnLocals = {$id: hashKey}; 31360 31361 if (trackByExp) { 31362 trackByExpGetter = $parse(trackByExp); 31363 } else { 31364 trackByIdArrayFn = function(key, value) { 31365 return hashKey(value); 31366 }; 31367 trackByIdObjFn = function(key) { 31368 return key; 31369 }; 31370 } 31371 31372 return function ngRepeatLink($scope, $element, $attr, ctrl, $transclude) { 31373 31374 if (trackByExpGetter) { 31375 trackByIdExpFn = function(key, value, index) {
vendor: 14,348 bytes, lines 31376-31718
31376 // assign key, value, and $index to the locals so that they can be used in hash functions 31377 if (keyIdentifier) hashFnLocals[keyIdentifier] = key; 31378 hashFnLocals[valueIdentifier] = value; 31379 hashFnLocals.$index = index; 31380 return trackByExpGetter($scope, hashFnLocals); 31381 }; 31382 } 31383 31384 // Store a list of elements from previous run. This is a hash where key is the item from the 31385 // iterator, and the value is objects with following properties. 31386 // - scope: bound scope 31387 // - clone: previous element. 31388 // - index: position 31389 // 31390 // We are using no-proto object so that we don't need to guard against inherited props via 31391 // hasOwnProperty. 31392 var lastBlockMap = createMap(); 31393 31394 //watch props 31395 $scope.$watchCollection(rhs, function ngRepeatAction(collection) { 31396 var index, length, 31397 previousNode = $element[0], // node that cloned nodes should be inserted after 31398 // initialized to the comment node anchor 31399 nextNode, 31400 // Same as lastBlockMap but it has the current state. It will become the 31401 // lastBlockMap on the next iteration. 31402 nextBlockMap = createMap(), 31403 collectionLength, 31404 key, value, // key/value of iteration 31405 trackById, 31406 trackByIdFn, 31407 collectionKeys, 31408 block, // last object information {scope, element, id} 31409 nextBlockOrder, 31410 elementsToRemove; 31411 31412 if (aliasAs) { 31413 $scope[aliasAs] = collection; 31414 } 31415 31416 if (isArrayLike(collection)) { 31417 collectionKeys = collection; 31418 trackByIdFn = trackByIdExpFn || trackByIdArrayFn; 31419 } else { 31420 trackByIdFn = trackByIdExpFn || trackByIdObjFn; 31421 // if object, extract keys, in enumeration order, unsorted 31422 collectionKeys = []; 31423 for (var itemKey in collection) { 31424 if (hasOwnProperty.call(collection, itemKey) && itemKey.charAt(0) !== '$') { 31425 collectionKeys.push(itemKey); 31426 } 31427 } 31428 } 31429 31430 collectionLength = collectionKeys.length; 31431 nextBlockOrder = new Array(collectionLength); 31432 31433 // locate existing items 31434 for (index = 0; index < collectionLength; index++) { 31435 key = (collection === collectionKeys) ? index : collectionKeys[index]; 31436 value = collection[key]; 31437 trackById = trackByIdFn(key, value, index); 31438 if (lastBlockMap[trackById]) { 31439 // found previously seen block 31440 block = lastBlockMap[trackById]; 31441 delete lastBlockMap[trackById]; 31442 nextBlockMap[trackById] = block; 31443 nextBlockOrder[index] = block; 31444 } else if (nextBlockMap[trackById]) { 31445 // if collision detected. restore lastBlockMap and throw an error 31446 forEach(nextBlockOrder, function(block) { 31447 if (block && block.scope) lastBlockMap[block.id] = block; 31448 }); 31449 throw ngRepeatMinErr('dupes', 31450 'Duplicates in a repeater are not allowed. Use \'track by\' expression to specify unique keys. Repeater: {0}, Duplicate key: {1}, Duplicate value: {2}', 31451 expression, trackById, value); 31452 } else { 31453 // new never before seen block 31454 nextBlockOrder[index] = {id: trackById, scope: undefined, clone: undefined}; 31455 nextBlockMap[trackById] = true; 31456 } 31457 } 31458 31459 // remove leftover items 31460 for (var blockKey in lastBlockMap) { 31461 block = lastBlockMap[blockKey]; 31462 elementsToRemove = getBlockNodes(block.clone); 31463 $animate.leave(elementsToRemove); 31464 if (elementsToRemove[0].parentNode) { 31465 // if the element was not removed yet because of pending animation, mark it as deleted 31466 // so that we can ignore it later 31467 for (index = 0, length = elementsToRemove.length; index < length; index++) { 31468 elementsToRemove[index][NG_REMOVED] = true; 31469 } 31470 } 31471 block.scope.$destroy(); 31472 } 31473 31474 // we are not using forEach for perf reasons (trying to avoid #call) 31475 for (index = 0; index < collectionLength; index++) { 31476 key = (collection === collectionKeys) ? index : collectionKeys[index]; 31477 value = collection[key]; 31478 block = nextBlockOrder[index]; 31479 31480 if (block.scope) { 31481 // if we have already seen this object, then we need to reuse the 31482 // associated scope/element 31483 31484 nextNode = previousNode; 31485 31486 // skip nodes that are already pending removal via leave animation 31487 do { 31488 nextNode = nextNode.nextSibling; 31489 } while (nextNode && nextNode[NG_REMOVED]); 31490 31491 if (getBlockStart(block) !== nextNode) { 31492 // existing item which got moved 31493 $animate.move(getBlockNodes(block.clone), null, previousNode); 31494 } 31495 previousNode = getBlockEnd(block); 31496 updateScope(block.scope, index, valueIdentifier, value, keyIdentifier, key, collectionLength); 31497 } else { 31498 // new item which we don't know about 31499 $transclude(function ngRepeatTransclude(clone, scope) { 31500 block.scope = scope; 31501 // http://jsperf.com/clone-vs-createcomment 31502 var endNode = ngRepeatEndComment.cloneNode(false); 31503 clone[clone.length++] = endNode; 31504 31505 $animate.enter(clone, null, previousNode); 31506 previousNode = endNode; 31507 // Note: We only need the first/last node of the cloned nodes. 31508 // However, we need to keep the reference to the jqlite wrapper as it might be changed later 31509 // by a directive with templateUrl when its template arrives. 31510 block.clone = clone; 31511 nextBlockMap[block.id] = block; 31512 updateScope(block.scope, index, valueIdentifier, value, keyIdentifier, key, collectionLength); 31513 }); 31514 } 31515 } 31516 lastBlockMap = nextBlockMap; 31517 }); 31518 }; 31519 } 31520 }; 31521}]; 31522 31523var NG_HIDE_CLASS = 'ng-hide'; 31524var NG_HIDE_IN_PROGRESS_CLASS = 'ng-hide-animate'; 31525/** 31526 * @ngdoc directive 31527 * @name ngShow 31528 * @multiElement 31529 * 31530 * @description 31531 * The `ngShow` directive shows or hides the given HTML element based on the expression provided to 31532 * the `ngShow` attribute. 31533 * 31534 * The element is shown or hidden by removing or adding the `.ng-hide` CSS class onto the element. 31535 * The `.ng-hide` CSS class is predefined in AngularJS and sets the display style to none (using an 31536 * `!important` flag). For CSP mode please add `angular-csp.css` to your HTML file (see 31537 * {@link ng.directive:ngCsp ngCsp}). 31538 * 31539 * ```html 31540 * <!-- when $scope.myValue is truthy (element is visible) --> 31541 * <div ng-show="myValue"></div> 31542 * 31543 * <!-- when $scope.myValue is falsy (element is hidden) --> 31544 * <div ng-show="myValue" class="ng-hide"></div> 31545 * ``` 31546 * 31547 * When the `ngShow` expression evaluates to a falsy value then the `.ng-hide` CSS class is added 31548 * to the class attribute on the element causing it to become hidden. When truthy, the `.ng-hide` 31549 * CSS class is removed from the element causing the element not to appear hidden. 31550 * 31551 * ## Why is `!important` used? 31552 * 31553 * You may be wondering why `!important` is used for the `.ng-hide` CSS class. This is because the 31554 * `.ng-hide` selector can be easily overridden by heavier selectors. For example, something as 31555 * simple as changing the display style on a HTML list item would make hidden elements appear 31556 * visible. This also becomes a bigger issue when dealing with CSS frameworks. 31557 * 31558 * By using `!important`, the show and hide behavior will work as expected despite any clash between 31559 * CSS selector specificity (when `!important` isn't used with any conflicting styles). If a 31560 * developer chooses to override the styling to change how to hide an element then it is just a 31561 * matter of using `!important` in their own CSS code. 31562 * 31563 * ### Overriding `.ng-hide` 31564 * 31565 * By default, the `.ng-hide` class will style the element with `display: none !important`. If you 31566 * wish to change the hide behavior with `ngShow`/`ngHide`, you can simply overwrite the styles for 31567 * the `.ng-hide` CSS class. Note that the selector that needs to be used is actually 31568 * `.ng-hide:not(.ng-hide-animate)` to cope with extra animation classes that can be added. 31569 * 31570 * ```css 31571 * .ng-hide:not(.ng-hide-animate) { 31572 * /* These are just alternative ways of hiding an element */ 31573 * display: block!important; 31574 * position: absolute; 31575 * top: -9999px; 31576 * left: -9999px; 31577 * } 31578 * ``` 31579 * 31580 * By default you don't need to override anything in CSS and the animations will work around the 31581 * display style. 31582 * 31583 * ## A note about animations with `ngShow` 31584 * 31585 * Animations in `ngShow`/`ngHide` work with the show and hide events that are triggered when the 31586 * directive expression is true and false. This system works like the animation system present with 31587 * `ngClass` except that you must also include the `!important` flag to override the display 31588 * property so that the elements are not actually hidden during the animation. 31589 * 31590 * ```css 31591 * /* A working example can be found at the bottom of this page. */ 31592 * .my-element.ng-hide-add, .my-element.ng-hide-remove { 31593 * transition: all 0.5s linear; 31594 * } 31595 * 31596 * .my-element.ng-hide-add { ... } 31597 * .my-element.ng-hide-add.ng-hide-add-active { ... } 31598 * .my-element.ng-hide-remove { ... } 31599 * .my-element.ng-hide-remove.ng-hide-remove-active { ... } 31600 * ``` 31601 * 31602 * Keep in mind that, as of AngularJS version 1.3, there is no need to change the display property 31603 * to block during animation states - ngAnimate will automatically handle the style toggling for you. 31604 * 31605 * @animations 31606 * | Animation | Occurs | 31607 * |-----------------------------------------------------|---------------------------------------------------------------------------------------------------------------| 31608 * | {@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. | 31609 * | {@link $animate#removeClass removeClass} `.ng-hide` | After the `ngShow` expression evaluates to a truthy value and just before contents are set to visible. | 31610 * 31611 * @element ANY 31612 * @param {expression} ngShow If the {@link guide/expression expression} is truthy/falsy then the 31613 * element is shown/hidden respectively. 31614 * 31615 * @example 31616 * A simple example, animating the element's opacity: 31617 * 31618 <example module="ngAnimate" deps="angular-animate.js" animations="true" name="ng-show-simple"> 31619 <file name="index.html"> 31620 Show: <input type="checkbox" ng-model="checked" aria-label="Toggle ngShow"><br /> 31621 <div class="check-element animate-show-hide" ng-show="checked"> 31622 I show up when your checkbox is checked. 31623 </div> 31624 </file> 31625 <file name="animations.css"> 31626 .animate-show-hide.ng-hide { 31627 opacity: 0; 31628 } 31629 31630 .animate-show-hide.ng-hide-add, 31631 .animate-show-hide.ng-hide-remove { 31632 transition: all linear 0.5s; 31633 } 31634 31635 .check-element { 31636 border: 1px solid black; 31637 opacity: 1; 31638 padding: 10px; 31639 } 31640 </file> 31641 <file name="protractor.js" type="protractor"> 31642 it('should check ngShow', function() { 31643 var checkbox = element(by.model('checked')); 31644 var checkElem = element(by.css('.check-element')); 31645 31646 expect(checkElem.isDisplayed()).toBe(false); 31647 checkbox.click(); 31648 expect(checkElem.isDisplayed()).toBe(true); 31649 }); 31650 </file> 31651 </example> 31652 * 31653 * <hr /> 31654 * @example 31655 * A more complex example, featuring different show/hide animations: 31656 * 31657 <example module="ngAnimate" deps="angular-animate.js" animations="true" name="ng-show-complex"> 31658 <file name="index.html"> 31659 Show: <input type="checkbox" ng-model="checked" aria-label="Toggle ngShow"><br /> 31660 <div class="check-element funky-show-hide" ng-show="checked"> 31661 I show up when your checkbox is checked. 31662 </div> 31663 </file> 31664 <file name="animations.css"> 31665 body { 31666 overflow: hidden; 31667 perspective: 1000px; 31668 } 31669 31670 .funky-show-hide.ng-hide-add { 31671 transform: rotateZ(0); 31672 transform-origin: right; 31673 transition: all 0.5s ease-in-out; 31674 } 31675 31676 .funky-show-hide.ng-hide-add.ng-hide-add-active { 31677 transform: rotateZ(-135deg); 31678 } 31679 31680 .funky-show-hide.ng-hide-remove { 31681 transform: rotateY(90deg); 31682 transform-origin: left; 31683 transition: all 0.5s ease; 31684 } 31685 31686 .funky-show-hide.ng-hide-remove.ng-hide-remove-active { 31687 transform: rotateY(0); 31688 } 31689 31690 .check-element { 31691 border: 1px solid black; 31692 opacity: 1; 31693 padding: 10px; 31694 } 31695 </file> 31696 <file name="protractor.js" type="protractor"> 31697 it('should check ngShow', function() { 31698 var checkbox = element(by.model('checked')); 31699 var checkElem = element(by.css('.check-element')); 31700 31701 expect(checkElem.isDisplayed()).toBe(false); 31702 checkbox.click(); 31703 expect(checkElem.isDisplayed()).toBe(true); 31704 }); 31705 </file> 31706 </example> 31707 */ 31708var ngShowDirective = ['$animate', function($animate) { 31709 return { 31710 restrict: 'A', 31711 multiElement: true, 31712 link: function(scope, element, attr) { 31713 scope.$watch(attr.ngShow, function ngShowWatchAction(value) { 31714 // we're adding a temporary, animation-specific class for ng-hide since this way 31715 // we can control when the element is actually displayed on screen without having 31716 // to have a global/greedy CSS selector that breaks when other animations are run. 31717 // Read: https://github.com/angular/angular.js/issues/9103#issuecomment-58335845 31718 $animate[value ? 'removeClass' : 'addClass'](element, NG_HIDE_CLASS, {
31719 tempClasses: NG_HIDE_IN_PROGRESS_CLASS 31720 }); 31721 }); 31722 } 31723 }; 31724}]; 31725 31726 31727/** 31728 * @ngdoc directive 31729 * @name ngHide 31730 * @multiElement 31731 * 31732 * @description 31733 * The `ngHide` directive shows or hides the given HTML element based on the expression provided to 31734 * the `ngHide` attribute. 31735 * 31736 * The element is shown or hidden by removing or adding the `.ng-hide` CSS class onto the element. 31737 * The `.ng-hide` CSS class is predefined in AngularJS and sets the display style to none (using an 31738 * `!important` flag). For CSP mode please add `angular-csp.css` to your HTML file (see 31739 * {@link ng.directive:ngCsp ngCsp}). 31740 * 31741 * ```html 31742 * <!-- when $scope.myValue is truthy (element is hidden) --> 31743 * <div ng-hide="myValue" class="ng-hide"></div> 31744 * 31745 * <!-- when $scope.myValue is falsy (element is visible) --> 31746 * <div ng-hide="myValue"></div> 31747 * ``` 31748 * 31749 * When the `ngHide` expression evaluates to a truthy value then the `.ng-hide` CSS class is added 31750 * to the class attribute on the element causing it to become hidden. When falsy, the `.ng-hide` 31751 * CSS class is removed from the element causing the element not to appear hidden. 31752 * 31753 * ## Why is `!important` used? 31754 * 31755 * You may be wondering why `!important` is used for the `.ng-hide` CSS class. This is because the 31756 * `.ng-hide` selector can be easily overridden by heavier selectors. For example, something as 31757 * simple as changing the display style on a HTML list item would make hidden elements appear 31758 * visible. This also becomes a bigger issue when dealing with CSS frameworks. 31759 * 31760 * By using `!important`, the show and hide behavior will work as expected despite any clash between 31761 * CSS selector specificity (when `!important` isn't used with any conflicting styles). If a 31762 * developer chooses to override the styling to change how to hide an element then it is just a 31763 * matter of using `!important` in their own CSS code. 31764 * 31765 * ### Overriding `.ng-hide` 31766 * 31767 * By default, the `.ng-hide` class will style the element with `display: none !important`. If you 31768 * wish to change the hide behavior with `ngShow`/`ngHide`, you can simply overwrite the styles for 31769 * the `.ng-hide` CSS class. Note that the selector that needs to be used is actually 31770 * `.ng-hide:not(.ng-hide-animate)` to cope with extra animation classes that can be added. 31771 * 31772 * ```css 31773 * .ng-hide:not(.ng-hide-animate) { 31774 * /* These are just alternative ways of hiding an element */ 31775 * display: block!important; 31776 * position: absolute; 31777 * top: -9999px; 31778 * left: -9999px; 31779 * } 31780 * ``` 31781 * 31782 * By default you don't need to override in CSS anything and the animations will work around the 31783 * display style. 31784 * 31785 * ## A note about animations with `ngHide` 31786 * 31787 * Animations in `ngShow`/`ngHide` work with the show and hide events that are triggered when the 31788 * directive expression is true and false. This system works like the animation system present with 31789 * `ngClass` except that you must also include the `!important` flag to override the display 31790 * property so that the elements are not actually hidden during the animation. 31791 * 31792 * ```css 31793 * /* A working example can be found at the bottom of this page. */ 31794 * .my-element.ng-hide-add, .my-element.ng-hide-remove { 31795 * transition: all 0.5s linear; 31796 * } 31797 * 31798 * .my-element.ng-hide-add { ... } 31799 * .my-element.ng-hide-add.ng-hide-add-active { ... } 31800 * .my-element.ng-hide-remove { ... } 31801 * .my-element.ng-hide-remove.ng-hide-remove-active { ... } 31802 * ``` 31803 * 31804 * Keep in mind that, as of AngularJS version 1.3, there is no need to change the display property 31805 * to block during animation states - ngAnimate will automatically handle the style toggling for you. 31806 * 31807 * @animations 31808 * | Animation | Occurs | 31809 * |-----------------------------------------------------|------------------------------------------------------------------------------------------------------------| 31810 * | {@link $animate#addClass addClass} `.ng-hide` | After the `ngHide` expression evaluates to a truthy value and just before the contents are set to hidden. | 31811 * | {@link $animate#removeClass removeClass} `.ng-hide` | After the `ngHide` expression evaluates to a non truthy value and just before contents are set to visible. | 31812 * 31813 * 31814 * @element ANY 31815 * @param {expression} ngHide If the {@link guide/expression expression} is truthy/falsy then the 31816 * element is hidden/shown respectively. 31817 * 31818 * @example 31819 * A simple example, animating the element's opacity: 31820 * 31821 <example module="ngAnimate" deps="angular-animate.js" animations="true" name="ng-hide-simple"> 31822 <file name="index.html"> 31823 Hide: <input type="checkbox" ng-model="checked" aria-label="Toggle ngHide"><br /> 31824 <div class="check-element animate-show-hide" ng-hide="checked"> 31825 I hide when your checkbox is checked. 31826 </div> 31827 </file> 31828 <file name="animations.css"> 31829 .animate-show-hide.ng-hide { 31830 opacity: 0; 31831 } 31832 31833 .animate-show-hide.ng-hide-add, 31834 .animate-show-hide.ng-hide-remove { 31835 transition: all linear 0.5s; 31836 } 31837 31838 .check-element { 31839 border: 1px solid black; 31840 opacity: 1; 31841 padding: 10px; 31842 } 31843 </file> 31844 <file name="protractor.js" type="protractor"> 31845 it('should check ngHide', function() { 31846 var checkbox = element(by.model('checked')); 31847 var checkElem = element(by.css('.check-element')); 31848 31849 expect(checkElem.isDisplayed()).toBe(true); 31850 checkbox.click(); 31851 expect(checkElem.isDisplayed()).toBe(false); 31852 }); 31853 </file> 31854 </example> 31855 * 31856 * <hr /> 31857 * @example 31858 * A more complex example, featuring different show/hide animations: 31859 * 31860 <example module="ngAnimate" deps="angular-animate.js" animations="true" name="ng-hide-complex"> 31861 <file name="index.html"> 31862 Hide: <input type="checkbox" ng-model="checked" aria-label="Toggle ngHide"><br /> 31863 <div class="check-element funky-show-hide" ng-hide="checked"> 31864 I hide when your checkbox is checked. 31865 </div> 31866 </file> 31867 <file name="animations.css"> 31868 body { 31869 overflow: hidden; 31870 perspective: 1000px; 31871 } 31872 31873 .funky-show-hide.ng-hide-add { 31874 transform: rotateZ(0); 31875 transform-origin: right; 31876 transition: all 0.5s ease-in-out; 31877 } 31878 31879 .funky-show-hide.ng-hide-add.ng-hide-add-active { 31880 transform: rotateZ(-135deg); 31881 } 31882 31883 .funky-show-hide.ng-hide-remove { 31884 transform: rotateY(90deg); 31885 transform-origin: left; 31886 transition: all 0.5s ease; 31887 } 31888 31889 .funky-show-hide.ng-hide-remove.ng-hide-remove-active { 31890 transform: rotateY(0); 31891 } 31892 31893 .check-element { 31894 border: 1px solid black; 31895 opacity: 1; 31896 padding: 10px; 31897 } 31898 </file> 31899 <file name="protractor.js" type="protractor"> 31900 it('should check ngHide', function() { 31901 var checkbox = element(by.model('checked')); 31902 var checkElem = element(by.css('.check-element')); 31903 31904 expect(checkElem.isDisplayed()).toBe(true); 31905 checkbox.click(); 31906 expect(checkElem.isDisplayed()).toBe(false); 31907 }); 31908 </file> 31909 </example> 31910 */ 31911var ngHideDirective = ['$animate', function($animate) { 31912 return { 31913 restrict: 'A', 31914 multiElement: true, 31915 link: function(scope, element, attr) { 31916 scope.$watch(attr.ngHide, function ngHideWatchAction(value) { 31917 // The comment inside of the ngShowDirective explains why we add and 31918 // remove a temporary class for the show/hide animation 31919 $animate[value ? 'addClass' : 'removeClass'](element,NG_HIDE_CLASS, {
31920 tempClasses: NG_HIDE_IN_PROGRESS_CLASS 31921 }); 31922 }); 31923 } 31924 }; 31925}]; 31926 31927/** 31928 * @ngdoc directive 31929 * @name ngStyle 31930 * @restrict AC 31931 * 31932 * @description 31933 * The `ngStyle` directive allows you to set CSS style on an HTML element conditionally. 31934 * 31935 * @knownIssue 31936 * You should not use {@link guide/interpolation interpolation} in the value of the `style` 31937 * attribute, when using the `ngStyle` directive on the same element. 31938 * See {@link guide/interpolation#known-issues here} for more info. 31939 * 31940 * @element ANY 31941 * @param {expression} ngStyle 31942 * 31943 * {@link guide/expression Expression} which evals to an 31944 * object whose keys are CSS style names and values are corresponding values for those CSS 31945 * keys. 31946 * 31947 * Since some CSS style names are not valid keys for an object, they must be quoted. 31948 * See the 'background-color' style in the example below. 31949 * 31950 * @example 31951 <example name="ng-style"> 31952 <file name="index.html"> 31953 <input type="button" value="set color" ng-click="myStyle={color:'red'}"> 31954 <input type="button" value="set background" ng-click="myStyle={'background-color':'blue'}"> 31955 <input type="button" value="clear" ng-click="myStyle={}"> 31956 <br/> 31957 <span ng-style="myStyle">Sample Text</span> 31958 <pre>myStyle={{myStyle}}</pre> 31959 </file> 31960 <file name="style.css"> 31961 span { 31962 color: black; 31963 } 31964 </file> 31965 <file name="protractor.js" type="protractor"> 31966 var colorSpan = element(by.css('span')); 31967 31968 it('should check ng-style', function() { 31969 expect(colorSpan.getCssValue('color')).toBe('rgba(0, 0, 0, 1)'); 31970 element(by.css('input[value=\'set color\']')).click(); 31971 expect(colorSpan.getCssValue('color')).toBe('rgba(255, 0, 0, 1)'); 31972 element(by.css('input[value=clear]')).click(); 31973 expect(colorSpan.getCssValue('color')).toBe('rgba(0, 0, 0, 1)'); 31974 }); 31975 </file> 31976 </example> 31977 */ 31978var ngStyleDirective = ngDirective(function(scope, element, attr) { 31979 scope.$watch(attr.ngStyle, function ngStyleWatchAction(newStyles, oldStyles) { 31980 if (oldStyles && (newStyles !== oldStyles)) { 31981 forEach(oldStyles, function(val, style) { element.css(style, '');}); 31982 } 31983 if (newStyles) element.css(newStyles); 31984 }, true
vendor: 15,211 bytes, lines 31984-32373
31984); 31985}); 31986 31987/** 31988 * @ngdoc directive 31989 * @name ngSwitch 31990 * @restrict EA 31991 * 31992 * @description 31993 * The `ngSwitch` directive is used to conditionally swap DOM structure on your template based on a scope expression. 31994 * Elements within `ngSwitch` but without `ngSwitchWhen` or `ngSwitchDefault` directives will be preserved at the location 31995 * as specified in the template. 31996 * 31997 * The directive itself works similar to ngInclude, however, instead of downloading template code (or loading it 31998 * from the template cache), `ngSwitch` simply chooses one of the nested elements and makes it visible based on which element 31999 * matches the value obtained from the evaluated expression. In other words, you define a container element 32000 * (where you place the directive), place an expression on the **`on="..."` attribute** 32001 * (or the **`ng-switch="..."` attribute**), define any inner elements inside of the directive and place 32002 * a when attribute per element. The when attribute is used to inform ngSwitch which element to display when the on 32003 * expression is evaluated. If a matching expression is not found via a when attribute then an element with the default 32004 * attribute is displayed. 32005 * 32006 * <div class="alert alert-info"> 32007 * Be aware that the attribute values to match against cannot be expressions. They are interpreted 32008 * as literal string values to match against. 32009 * For example, **`ng-switch-when="someVal"`** will match against the string `"someVal"` not against the 32010 * value of the expression `$scope.someVal`. 32011 * </div> 32012 32013 * @animations 32014 * | Animation | Occurs | 32015 * |----------------------------------|-------------------------------------| 32016 * | {@link ng.$animate#enter enter} | after the ngSwitch contents change and the matched child element is placed inside the container | 32017 * | {@link ng.$animate#leave leave} | after the ngSwitch contents change and just before the former contents are removed from the DOM | 32018 * 32019 * @usage 32020 * 32021 * ``` 32022 * <ANY ng-switch="expression"> 32023 * <ANY ng-switch-when="matchValue1">...</ANY> 32024 * <ANY ng-switch-when="matchValue2">...</ANY> 32025 * <ANY ng-switch-default>...</ANY> 32026 * </ANY> 32027 * ``` 32028 * 32029 * 32030 * @scope 32031 * @priority 1200 32032 * @param {*} ngSwitch|on expression to match against <code>ng-switch-when</code>. 32033 * On child elements add: 32034 * 32035 * * `ngSwitchWhen`: the case statement to match against. If match then this 32036 * case will be displayed. If the same match appears multiple times, all the 32037 * elements will be displayed. It is possible to associate multiple values to 32038 * the same `ngSwitchWhen` by defining the optional attribute 32039 * `ngSwitchWhenSeparator`. The separator will be used to split the value of 32040 * the `ngSwitchWhen` attribute into multiple tokens, and the element will show 32041 * if any of the `ngSwitch` evaluates to any of these tokens. 32042 * * `ngSwitchDefault`: the default case when no other case match. If there 32043 * are multiple default cases, all of them will be displayed when no other 32044 * case match. 32045 * 32046 * 32047 * @example 32048 <example module="switchExample" deps="angular-animate.js" animations="true" name="ng-switch"> 32049 <file name="index.html"> 32050 <div ng-controller="ExampleController"> 32051 <select ng-model="selection" ng-options="item for item in items"> 32052 </select> 32053 <code>selection={{selection}}</code> 32054 <hr/> 32055 <div class="animate-switch-container" 32056 ng-switch on="selection"> 32057 <div class="animate-switch" ng-switch-when="settings|options" ng-switch-when-separator="|">Settings Div</div> 32058 <div class="animate-switch" ng-switch-when="home">Home Span</div> 32059 <div class="animate-switch" ng-switch-default>default</div> 32060 </div> 32061 </div> 32062 </file> 32063 <file name="script.js"> 32064 angular.module('switchExample', ['ngAnimate']) 32065 .controller('ExampleController', ['$scope', function($scope) { 32066 $scope.items = ['settings', 'home', 'options', 'other']; 32067 $scope.selection = $scope.items[0]; 32068 }]); 32069 </file> 32070 <file name="animations.css"> 32071 .animate-switch-container { 32072 position:relative; 32073 background:white; 32074 border:1px solid black; 32075 height:40px; 32076 overflow:hidden; 32077 } 32078 32079 .animate-switch { 32080 padding:10px; 32081 } 32082 32083 .animate-switch.ng-animate { 32084 transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s; 32085 32086 position:absolute; 32087 top:0; 32088 left:0; 32089 right:0; 32090 bottom:0; 32091 } 32092 32093 .animate-switch.ng-leave.ng-leave-active, 32094 .animate-switch.ng-enter { 32095 top:-50px; 32096 } 32097 .animate-switch.ng-leave, 32098 .animate-switch.ng-enter.ng-enter-active { 32099 top:0; 32100 } 32101 </file> 32102 <file name="protractor.js" type="protractor"> 32103 var switchElem = element(by.css('[ng-switch]')); 32104 var select = element(by.model('selection')); 32105 32106 it('should start in settings', function() { 32107 expect(switchElem.getText()).toMatch(/Settings Div/); 32108 }); 32109 it('should change to home', function() { 32110 select.all(by.css('option')).get(1).click(); 32111 expect(switchElem.getText()).toMatch(/Home Span/); 32112 }); 32113 it('should change to settings via "options"', function() { 32114 select.all(by.css('option')).get(2).click(); 32115 expect(switchElem.getText()).toMatch(/Settings Div/); 32116 }); 32117 it('should select default', function() { 32118 select.all(by.css('option')).get(3).click(); 32119 expect(switchElem.getText()).toMatch(/default/); 32120 }); 32121 </file> 32122 </example> 32123 */ 32124var ngSwitchDirective = ['$animate', '$compile', function($animate, $compile) { 32125 return { 32126 require: 'ngSwitch', 32127 32128 // asks for $scope to fool the BC controller module 32129 controller: ['$scope', function NgSwitchController() { 32130 this.cases = {}; 32131 }], 32132 link: function(scope, element, attr, ngSwitchController) { 32133 var watchExpr = attr.ngSwitch || attr.on, 32134 selectedTranscludes = [], 32135 selectedElements = [], 32136 previousLeaveAnimations = [], 32137 selectedScopes = []; 32138 32139 var spliceFactory = function(array, index) { 32140 return function(response) { 32141 if (response !== false) array.splice(index, 1); 32142 }; 32143 }; 32144 32145 scope.$watch(watchExpr, function ngSwitchWatchAction(value) { 32146 var i, ii; 32147 32148 // Start with the last, in case the array is modified during the loop 32149 while (previousLeaveAnimations.length) { 32150 $animate.cancel(previousLeaveAnimations.pop()); 32151 } 32152 32153 for (i = 0, ii = selectedScopes.length; i < ii; ++i) { 32154 var selected = getBlockNodes(selectedElements[i].clone); 32155 selectedScopes[i].$destroy(); 32156 var runner = previousLeaveAnimations[i] = $animate.leave(selected); 32157 runner.done(spliceFactory(previousLeaveAnimations, i)); 32158 } 32159 32160 selectedElements.length = 0; 32161 selectedScopes.length = 0; 32162 32163 if ((selectedTranscludes = ngSwitchController.cases['!' + value] || ngSwitchController.cases['?'])) { 32164 forEach(selectedTranscludes, function(selectedTransclude) { 32165 selectedTransclude.transclude(function(caseElement, selectedScope) { 32166 selectedScopes.push(selectedScope); 32167 var anchor = selectedTransclude.element; 32168 caseElement[caseElement.length++] = $compile.$$createComment('end ngSwitchWhen'); 32169 var block = { clone: caseElement }; 32170 32171 selectedElements.push(block); 32172 $animate.enter(caseElement, anchor.parent(), anchor); 32173 }); 32174 }); 32175 } 32176 }); 32177 } 32178 }; 32179}]; 32180 32181var ngSwitchWhenDirective = ngDirective({ 32182 transclude: 'element', 32183 priority: 1200, 32184 require: '^ngSwitch', 32185 multiElement: true, 32186 link: function(scope, element, attrs, ctrl, $transclude) { 32187 32188 var cases = attrs.ngSwitchWhen.split(attrs.ngSwitchWhenSeparator).sort().filter( 32189 // Filter duplicate cases 32190 function(element, index, array) { return array[index - 1] !== element; } 32191 ); 32192 32193 forEach(cases, function(whenCase) { 32194 ctrl.cases['!' + whenCase] = (ctrl.cases['!' + whenCase] || []); 32195 ctrl.cases['!' + whenCase].push({ transclude: $transclude, element: element }); 32196 }); 32197 } 32198}); 32199 32200var ngSwitchDefaultDirective = ngDirective({ 32201 transclude: 'element', 32202 priority: 1200, 32203 require: '^ngSwitch', 32204 multiElement: true, 32205 link: function(scope, element, attr, ctrl, $transclude) { 32206 ctrl.cases['?'] = (ctrl.cases['?'] || []); 32207 ctrl.cases['?'].push({ transclude: $transclude, element: element }); 32208 } 32209}); 32210 32211/** 32212 * @ngdoc directive 32213 * @name ngTransclude 32214 * @restrict EAC 32215 * 32216 * @description 32217 * Directive that marks the insertion point for the transcluded DOM of the nearest parent directive that uses transclusion. 32218 * 32219 * You can specify that you want to insert a named transclusion slot, instead of the default slot, by providing the slot name 32220 * as the value of the `ng-transclude` or `ng-transclude-slot` attribute. 32221 * 32222 * If the transcluded content is not empty (i.e. contains one or more DOM nodes, including whitespace text nodes), any existing 32223 * content of this element will be removed before the transcluded content is inserted. 32224 * If the transcluded content is empty (or only whitespace), the existing content is left intact. This lets you provide fallback 32225 * content in the case that no transcluded content is provided. 32226 * 32227 * @element ANY 32228 * 32229 * @param {string} ngTransclude|ngTranscludeSlot the name of the slot to insert at this point. If this is not provided, is empty 32230 * or its value is the same as the name of the attribute then the default slot is used. 32231 * 32232 * @example 32233 * ### Basic transclusion 32234 * This example demonstrates basic transclusion of content into a component directive. 32235 * <example name="simpleTranscludeExample" module="transcludeExample"> 32236 * <file name="index.html"> 32237 * <script> 32238 * angular.module('transcludeExample', []) 32239 * .directive('pane', function(){ 32240 * return { 32241 * restrict: 'E', 32242 * transclude: true, 32243 * scope: { title:'@' }, 32244 * template: '<div style="border: 1px solid black;">' + 32245 * '<div style="background-color: gray">{{title}}</div>' + 32246 * '<ng-transclude></ng-transclude>' + 32247 * '</div>' 32248 * }; 32249 * }) 32250 * .controller('ExampleController', ['$scope', function($scope) { 32251 * $scope.title = 'Lorem Ipsum'; 32252 * $scope.text = 'Neque porro quisquam est qui dolorem ipsum quia dolor...'; 32253 * }]); 32254 * </script> 32255 * <div ng-controller="ExampleController"> 32256 * <input ng-model="title" aria-label="title"> <br/> 32257 * <textarea ng-model="text" aria-label="text"></textarea> <br/> 32258 * <pane title="{{title}}"><span>{{text}}</span></pane> 32259 * </div> 32260 * </file> 32261 * <file name="protractor.js" type="protractor"> 32262 * it('should have transcluded', function() { 32263 * var titleElement = element(by.model('title')); 32264 * titleElement.clear(); 32265 * titleElement.sendKeys('TITLE'); 32266 * var textElement = element(by.model('text')); 32267 * textElement.clear(); 32268 * textElement.sendKeys('TEXT'); 32269 * expect(element(by.binding('title')).getText()).toEqual('TITLE'); 32270 * expect(element(by.binding('text')).getText()).toEqual('TEXT'); 32271 * }); 32272 * </file> 32273 * </example> 32274 * 32275 * @example 32276 * ### Transclude fallback content 32277 * This example shows how to use `NgTransclude` with fallback content, that 32278 * is displayed if no transcluded content is provided. 32279 * 32280 * <example module="transcludeFallbackContentExample" name="ng-transclude"> 32281 * <file name="index.html"> 32282 * <script> 32283 * angular.module('transcludeFallbackContentExample', []) 32284 * .directive('myButton', function(){ 32285 * return { 32286 * restrict: 'E', 32287 * transclude: true, 32288 * scope: true, 32289 * template: '<button style="cursor: pointer;">' + 32290 * '<ng-transclude>' + 32291 * '<b style="color: red;">Button1</b>' + 32292 * '</ng-transclude>' + 32293 * '</button>' 32294 * }; 32295 * }); 32296 * </script> 32297 * <!-- fallback button content --> 32298 * <my-button id="fallback"></my-button> 32299 * <!-- modified button content --> 32300 * <my-button id="modified"> 32301 * <i style="color: green;">Button2</i> 32302 * </my-button> 32303 * </file> 32304 * <file name="protractor.js" type="protractor"> 32305 * it('should have different transclude element content', function() { 32306 * expect(element(by.id('fallback')).getText()).toBe('Button1'); 32307 * expect(element(by.id('modified')).getText()).toBe('Button2'); 32308 * }); 32309 * </file> 32310 * </example> 32311 * 32312 * @example 32313 * ### Multi-slot transclusion 32314 * This example demonstrates using multi-slot transclusion in a component directive. 32315 * <example name="multiSlotTranscludeExample" module="multiSlotTranscludeExample"> 32316 * <file name="index.html"> 32317 * <style> 32318 * .title, .footer { 32319 * background-color: gray 32320 * } 32321 * </style> 32322 * <div ng-controller="ExampleController"> 32323 * <input ng-model="title" aria-label="title"> <br/> 32324 * <textarea ng-model="text" aria-label="text"></textarea> <br/> 32325 * <pane> 32326 * <pane-title><a ng-href="{{link}}">{{title}}</a></pane-title> 32327 * <pane-body><p>{{text}}</p></pane-body> 32328 * </pane> 32329 * </div> 32330 * </file> 32331 * <file name="app.js"> 32332 * angular.module('multiSlotTranscludeExample', []) 32333 * .directive('pane', function() { 32334 * return { 32335 * restrict: 'E', 32336 * transclude: { 32337 * 'title': '?paneTitle', 32338 * 'body': 'paneBody', 32339 * 'footer': '?paneFooter' 32340 * }, 32341 * template: '<div style="border: 1px solid black;">' + 32342 * '<div class="title" ng-transclude="title">Fallback Title</div>' + 32343 * '<div ng-transclude="body"></div>' + 32344 * '<div class="footer" ng-transclude="footer">Fallback Footer</div>' + 32345 * '</div>' 32346 * }; 32347 * }) 32348 * .controller('ExampleController', ['$scope', function($scope) { 32349 * $scope.title = 'Lorem Ipsum'; 32350 * $scope.link = 'https://google.com'; 32351 * $scope.text = 'Neque porro quisquam est qui dolorem ipsum quia dolor...'; 32352 * }]); 32353 * </file> 32354 * <file name="protractor.js" type="protractor"> 32355 * it('should have transcluded the title and the body', function() { 32356 * var titleElement = element(by.model('title')); 32357 * titleElement.clear(); 32358 * titleElement.sendKeys('TITLE'); 32359 * var textElement = element(by.model('text')); 32360 * textElement.clear(); 32361 * textElement.sendKeys('TEXT'); 32362 * expect(element(by.css('.title')).getText()).toEqual('TITLE'); 32363 * expect(element(by.binding('text')).getText()).toEqual('TEXT'); 32364 * expect(element(by.css('.footer')).getText()).toEqual('Fallback Footer'); 32365 * }); 32366 * </file> 32367 * </example> 32368 */ 32369var ngTranscludeMinErr = minErr('ngTransclude'); 32370var ngTranscludeDirective = ['$compile', function($compile) { 32371 return { 32372 restrict: 'EAC', 32373
32373terminal: true
vendor: 5,603 bytes, lines 32373-32526
32373, 32374 compile: function ngTranscludeCompile(tElement) { 32375 32376 // Remove and cache any original content to act as a fallback 32377 var fallbackLinkFn = $compile(tElement.contents()); 32378 tElement.empty(); 32379 32380 return function ngTranscludePostLink($scope, $element, $attrs, controller, $transclude) { 32381 32382 if (!$transclude) { 32383 throw ngTranscludeMinErr('orphan', 32384 'Illegal use of ngTransclude directive in the template! ' + 32385 'No parent directive that requires a transclusion found. ' + 32386 'Element: {0}', 32387 startingTag($element)); 32388 } 32389 32390 32391 // If the attribute is of the form: `ng-transclude="ng-transclude"` then treat it like the default 32392 if ($attrs.ngTransclude === $attrs.$attr.ngTransclude) { 32393 $attrs.ngTransclude = ''; 32394 } 32395 var slotName = $attrs.ngTransclude || $attrs.ngTranscludeSlot; 32396 32397 // If the slot is required and no transclusion content is provided then this call will throw an error 32398 $transclude(ngTranscludeCloneAttachFn, null, slotName); 32399 32400 // If the slot is optional and no transclusion content is provided then use the fallback content 32401 if (slotName && !$transclude.isSlotFilled(slotName)) { 32402 useFallbackContent(); 32403 } 32404 32405 function ngTranscludeCloneAttachFn(clone, transcludedScope) { 32406 if (clone.length && notWhitespace(clone)) { 32407 $element.append(clone); 32408 } else { 32409 useFallbackContent(); 32410 // There is nothing linked against the transcluded scope since no content was available, 32411 // so it should be safe to clean up the generated scope. 32412 transcludedScope.$destroy(); 32413 } 32414 } 32415 32416 function useFallbackContent() { 32417 // Since this is the fallback content rather than the transcluded content, 32418 // we link against the scope of this directive rather than the transcluded scope 32419 fallbackLinkFn($scope, function(clone) { 32420 $element.append(clone); 32421 }); 32422 } 32423 32424 function notWhitespace(nodes) { 32425 for (var i = 0, ii = nodes.length; i < ii; i++) { 32426 var node = nodes[i]; 32427 if (node.nodeType !== NODE_TYPE_TEXT || node.nodeValue.trim()) { 32428 return true; 32429 } 32430 } 32431 } 32432 }; 32433 } 32434 }; 32435}]; 32436 32437/** 32438 * @ngdoc directive 32439 * @name script 32440 * @restrict E 32441 * 32442 * @description 32443 * Load the content of a `<script>` element into {@link ng.$templateCache `$templateCache`}, so that the 32444 * template can be used by {@link ng.directive:ngInclude `ngInclude`}, 32445 * {@link ngRoute.directive:ngView `ngView`}, or {@link guide/directive directives}. The type of the 32446 * `<script>` element must be specified as `text/ng-template`, and a cache name for the template must be 32447 * assigned through the element's `id`, which can then be used as a directive's `templateUrl`. 32448 * 32449 * @param {string} type Must be set to `'text/ng-template'`. 32450 * @param {string} id Cache name of the template. 32451 * 32452 * @example 32453 <example name="script-tag"> 32454 <file name="index.html"> 32455 <script type="text/ng-template" id="/tpl.html"> 32456 Content of the template. 32457 </script> 32458 32459 <a ng-click="currentTpl='/tpl.html'" id="tpl-link">Load inlined template</a> 32460 <div id="tpl-content" ng-include src="currentTpl"></div> 32461 </file> 32462 <file name="protractor.js" type="protractor"> 32463 it('should load template defined inside script tag', function() { 32464 element(by.css('#tpl-link')).click(); 32465 expect(element(by.css('#tpl-content')).getText()).toMatch(/Content of the template/); 32466 }); 32467 </file> 32468 </example> 32469 */ 32470var scriptDirective = ['$templateCache', function($templateCache) { 32471 return { 32472 restrict: 'E', 32473 terminal: true, 32474 compile: function(element, attr) { 32475 if (attr.type === 'text/ng-template') { 32476 var templateUrl = attr.id, 32477 text = element[0].text; 32478 32479 $templateCache.put(templateUrl, text); 32480 } 32481 } 32482 }; 32483}]; 32484 32485/* exported selectDirective, optionDirective */ 32486 32487var noopNgModelController = { $setViewValue: noop, $render: noop }; 32488 32489function setOptionSelectedStatus(optionEl, value) { 32490 optionEl.prop('selected', value); 32491 /** 32492 * When unselecting an option, setting the property to null / false should be enough 32493 * However, screenreaders might react to the selected attribute instead, see 32494 * https://github.com/angular/angular.js/issues/14419 32495 * Note: "selected" is a boolean attr and will be removed when the "value" arg in attr() is false 32496 * or null 32497 */ 32498 optionEl.attr('selected', value); 32499} 32500 32501/** 32502 * @ngdoc type 32503 * @name select.SelectController 32504 * 32505 * @description 32506 * The controller for the {@link ng.select select} directive. The controller exposes 32507 * a few utility methods that can be used to augment the behavior of a regular or an 32508 * {@link ng.ngOptions ngOptions} select element. 32509 * 32510 * @example 32511 * ### Set a custom error when the unknown option is selected 32512 * 32513 * This example sets a custom error "unknownValue" on the ngModelController 32514 * when the select element's unknown option is selected, i.e. when the model is set to a value 32515 * that is not matched by any option. 32516 * 32517 * <example name="select-unknown-value-error" module="staticSelect"> 32518 * <file name="index.html"> 32519 * <div ng-controller="ExampleController"> 32520 * <form name="myForm"> 32521 * <label for="testSelect"> Single select: </label><br> 32522 * <select name="testSelect" ng-model="selected" unknown-value-error> 32523 * <option value="option-1">Option 1</option> 32524 * <option value="option-2">Option 2</option> 32525 * </select><br> 32526 * <span
32526ng-if="myForm.testSelect.$error.unknownValue">Error: The current model doesn't match any option</span> 32527 * 32528 * <button ng-click="forceUnknownOption()">Force unknown option</button><br> 32529 * </form> 32530 * </div> 32531 * </file> 32532 * <file name="app.js"> 32533 * angular.module('staticSelect', []) 32534 * .controller('ExampleController', ['$scope', function($scope) { 32535 * $scope.selected = null; 32536 * 32537 * $scope.forceUnknownOption = function() { 32538 * $scope.selected = 'nonsense'; 32539 * }; 32540 * }]) 32541 * .directive('unknownValueError', function() { 32542 * return { 32543 * require: ['ngModel', 'select'], 32544 * link: function(scope, element, attrs, ctrls) { 32545 * var ngModelCtrl = ctrls[0]; 32546 * var selectCtrl = ctrls[1]; 32547 * 32548 * ngModelCtrl.$validators.unknownValue = function(modelValue, viewValue) { 32549 * if (selectCtrl.$isUnknownOptionSelected()) { 32550 * return false; 32551 * } 32552 * 32553 * return true; 32554 * }; 32555 * } 32556 * 32557 * }; 32558 * }); 32559 * </file> 32560 *</example> 32561 * 32562 * 32563 * @example 32564 * ### Set the "required" error when the unknown option is selected. 32565 * 32566 * By default, the "required" error on the ngModelController is only set on a required select 32567 * when the empty option is selected. This example adds a custom directive that also sets the 32568 * error when the unknown option is selected. 32569 * 32570 * <example name="select-unknown-value-required" module="staticSelect"> 32571 * <file name="index.html">
32572 * <div ng-controller="ExampleController"> 32573 * <form name="myForm"> 32574 * <label for="testSelect"> Select: </label><br> 32575 * <select name="testSelect" ng-model="selected" unknown-value-required> 32576 * <option value="option-1">Option 1</option> 32577 * <option value="option-2">Option 2</option> 32578 * </select><br> 32579 * <span ng-if="myForm.testSelect.$error.required">Error: Please select a value</span><br> 32580 * 32581 * <button ng-click="forceUnknownOption()">Force unknown option</button><br> 32582 * </form> 32583 * </div> 32584 * </file> 32585 * <file name="app.js"> 32586 * angular.module('staticSelect', []) 32587 * .controller('ExampleController', ['$scope', function($scope) { 32588 * $scope.selected = null; 32589 * 32590 * $scope.forceUnknownOption = function() { 32591 * $scope.selected = 'nonsense'; 32592 * }; 32593 * }]) 32594 * .directive('unknownValueRequired', function() { 32595 * return { 32596 * priority: 1, // This directive must run after the required directive has added its validator 32597 * require: ['ngModel', 'select'], 32598 * link: function(scope, element, attrs, ctrls) { 32599 * var ngModelCtrl = ctrls[0]; 32600 * var selectCtrl = ctrls[1]; 32601 * 32602 * var originalRequiredValidator = ngModelCtrl.$validators.required; 32603 * 32604 * ngModelCtrl.$validators.required = function() { 32605 * if (attrs.required && selectCtrl.$isUnknownOptionSelected()) { 32606 * return false; 32607 * } 32608 * 32609 * return originalRequiredValidator.apply(this, arguments); 32610 * }; 32611 * } 32612 * }; 32613 * }); 32614 * </file> 32615 *</example> 32616 * 32617 * 32618 */ 32619var SelectController = 32620 ['$element', '$scope', /** @this */ function($element, $scope) { 32621 32622 var self = this, 32623 optionsMap = new NgMap(); 32624 32625 self.selectValueMap = {}; // Keys are the hashed values, values the original values 32626 32627 // If the ngModel doesn't get provided then provide a dummy noop version to prevent errors 32628 self.ngModelCtrl = noopNgModelController; 32629 self.multiple = false; 32630 32631 // The "unknown" option is one that is prepended to the list if the viewValue 32632 // does not match any of the options. When it is rendered the value of the unknown 32633 // option is '? XXX ?' where XXX is the hashKey of the value that is not known. 32634 // 32635 // Support: IE 9 only 32636 // We can't just jqLite('<option>') since jqLite is not smart enough 32637 // to create it in <select> and IE barfs otherwise. 32638 self.unknownOption = jqLite(window.document.createElement('option')); 32639 32640 // The empty option is an option with the value '' that the application developer can 32641 // provide inside the select. It is always selectable and indicates that a "null" selection has 32642 // been made by the user. 32643 // If the select has an empty option, and the model of the select is set to "undefined" or "null", 32644 // the empty option is selected. 32645 // If the model is set to a different unmatched value, the unknown option is rendered and 32646 // selected, i.e both are present, because a "null" selection and an unknown value are different. 32647 self.hasEmptyOption = false; 32648 self.emptyOption = undefined; 32649 32650 self.renderUnknownOption = function(val) { 32651 var unknownVal = self.generateUnknownOptionValue(val); 32652 self.unknownOption.val(unknownVal); 32653 $element.prepend(self.unknownOption); 32654 setOptionSelectedStatus(self.unknownOption, true); 32655 $element.val(unknownVal); 32656 }; 32657 32658 self.updateUnknownOption = function(val) { 32659 var unknownVal = self.generateUnknownOptionValue(val); 32660 self.unknownOption.val(unknownVal); 32661 setOptionSelectedStatus(self.unknownOption, true); 32662 $element.val(unknownVal); 32663 }; 32664 32665 self.generateUnknownOptionValue = function(val) { 32666 return '? ' + hashKey(val) + ' ?'; 32667 }; 32668 32669 self.removeUnknownOption = function() { 32670 if (self.unknownOption.parent()) self.unknownOption.remove(); 32671 }; 32672 32673 self.selectEmptyOption = function() { 32674 if (self.emptyOption) { 32675 $element.val(''); 32676 setOptionSelectedStatus(self.emptyOption, true); 32677 } 32678 }; 32679 32680 self.unselectEmptyOption = function() { 32681 if (self.hasEmptyOption) { 32682 setOptionSelectedStatus(self.emptyOption, false); 32683 } 32684 }; 32685 32686 $scope.$on('$destroy', function() { 32687 // disable unknown option so that we don't do work when the whole select is being destroyed 32688 self.renderUnknownOption = noop; 32689 }); 32690 32691 // Read the value of the select control, the implementation of this changes depending 32692 // upon whether the select can have multiple values and whether ngOptions is at work. 32693 self.readValue = function readSingleValue() { 32694 var val = $element.val(); 32695 // ngValue added option values are stored in the selectValueMap, normal interpolations are not 32696 var realVal = val in self.selectValueMap ? self.selectValueMap[val] : val; 32697 32698 if (self.hasOption(realVal)) { 32699 return realVal; 32700 } 32701 32702 return null; 32703 }; 32704 32705 32706 // Write the value to the select control, the implementation of this changes depending 32707 // upon whether the select can have multiple values and whether ngOptions is at work. 32708 self.writeValue = function writeSingleValue(value) { 32709 // Make sure to remove the selected attribute from the previously selected option 32710 // Otherwise, screen readers might get confused 32711 var currentlySelectedOption = $element[0].options[$element[0].selectedIndex]; 32712 if (currentlySelectedOption) setOptionSelectedStatus(jqLite(currentlySelectedOption), false); 32713 32714 if (self.hasOption(value)) { 32715 self.removeUnknownOption(); 32716 32717 var hashedVal = hashKey(value); 32718 $element.val(hashedVal in self.selectValueMap ? hashedVal : value); 32719 32720 // Set selected attribute and property on selected option for screen readers 32721 var selectedOption = $element[0].options[$element[0].selectedIndex]; 32722 setOptionSelectedStatus(jqLite(selectedOption), true); 32723 } else { 32724 self.selectUnknownOrEmptyOption(value); 32725 } 32726 }; 32727 32728 32729 // Tell the select control that an option, with the given value, has been added 32730 self.addOption = function(value, element) { 32731 // Skip comment nodes, as they only pollute the `optionsMap` 32732 if (element[0].nodeType === NODE_TYPE_COMMENT) return; 32733 32734 assertNotHasOwnProperty(value, '"option value"'); 32735 if (value === '') { 32736 self.hasEmptyOption = true; 32737 self.emptyOption = element; 32738 } 32739 var count = optionsMap.get(value) || 0; 32740 optionsMap.set(value, count + 1); 32741 // Only render at the end of a digest. This improves render performance when many options 32742 // are added during a digest and ensures all relevant options are correctly marked as selected 32743 scheduleRender(); 32744 }; 32745 32746 // Tell the select control that an option, with the given value, has been removed 32747 self.removeOption = function(value) { 32748 var count = optionsMap.get(value); 32749 if (count) { 32750 if (count === 1) { 32751 optionsMap.delete(value); 32752 if (value === '') { 32753 self.hasEmptyOption = false;
vendor: 6,620 bytes, lines 32754-32964
32754 self.emptyOption = undefined; 32755 } 32756 } else { 32757 optionsMap.set(value, count - 1); 32758 } 32759 } 32760 }; 32761 32762 // Check whether the select control has an option matching the given value 32763 self.hasOption = function(value) { 32764 return !!optionsMap.get(value); 32765 }; 32766 32767 /** 32768 * @ngdoc method 32769 * @name select.SelectController#$hasEmptyOption 32770 * 32771 * @description 32772 * 32773 * Returns `true` if the select element currently has an empty option 32774 * element, i.e. an option that signifies that the select is empty / the selection is null. 32775 * 32776 */ 32777 self.$hasEmptyOption = function() { 32778 return self.hasEmptyOption; 32779 }; 32780 32781 /** 32782 * @ngdoc method 32783 * @name select.SelectController#$isUnknownOptionSelected 32784 * 32785 * @description 32786 * 32787 * Returns `true` if the select element's unknown option is selected. The unknown option is added 32788 * and automatically selected whenever the select model doesn't match any option. 32789 * 32790 */ 32791 self.$isUnknownOptionSelected = function() { 32792 // Presence of the unknown option means it is selected 32793 return $element[0].options[0] === self.unknownOption[0]; 32794 }; 32795 32796 /** 32797 * @ngdoc method 32798 * @name select.SelectController#$isEmptyOptionSelected 32799 * 32800 * @description 32801 * 32802 * Returns `true` if the select element has an empty option and this empty option is currently 32803 * selected. Returns `false` if the select element has no empty option or it is not selected. 32804 * 32805 */ 32806 self.$isEmptyOptionSelected = function() { 32807 return self.hasEmptyOption && $element[0].options[$element[0].selectedIndex] === self.emptyOption[0]; 32808 }; 32809 32810 self.selectUnknownOrEmptyOption = function(value) { 32811 if (value == null && self.emptyOption) { 32812 self.removeUnknownOption(); 32813 self.selectEmptyOption(); 32814 } else if (self.unknownOption.parent().length) { 32815 self.updateUnknownOption(value); 32816 } else { 32817 self.renderUnknownOption(value); 32818 } 32819 }; 32820 32821 var renderScheduled = false; 32822 function scheduleRender() { 32823 if (renderScheduled) return; 32824 renderScheduled = true; 32825 $scope.$$postDigest(function() { 32826 renderScheduled = false; 32827 self.ngModelCtrl.$render(); 32828 }); 32829 } 32830 32831 var updateScheduled = false; 32832 function scheduleViewValueUpdate(renderAfter) { 32833 if (updateScheduled) return; 32834 32835 updateScheduled = true; 32836 32837 $scope.$$postDigest(function() { 32838 if ($scope.$$destroyed) return; 32839 32840 updateScheduled = false; 32841 self.ngModelCtrl.$setViewValue(self.readValue()); 32842 if (renderAfter) self.ngModelCtrl.$render(); 32843 }); 32844 } 32845 32846 32847 self.registerOption = function(optionScope, optionElement, optionAttrs, interpolateValueFn, interpolateTextFn) { 32848 32849 if (optionAttrs.$attr.ngValue) { 32850 // The value attribute is set by ngValue 32851 var oldVal, hashedVal = NaN; 32852 optionAttrs.$observe('value', function valueAttributeObserveAction(newVal) { 32853 32854 var removal; 32855 var previouslySelected = optionElement.prop('selected'); 32856 32857 if (isDefined(hashedVal)) { 32858 self.removeOption(oldVal); 32859 delete self.selectValueMap[hashedVal]; 32860 removal = true; 32861 } 32862 32863 hashedVal = hashKey(newVal); 32864 oldVal = newVal; 32865 self.selectValueMap[hashedVal] = newVal; 32866 self.addOption(newVal, optionElement); 32867 // Set the attribute directly instead of using optionAttrs.$set - this stops the observer 32868 // from firing a second time. Other $observers on value will also get the result of the 32869 // ngValue expression, not the hashed value 32870 optionElement.attr('value', hashedVal); 32871 32872 if (removal && previouslySelected) { 32873 scheduleViewValueUpdate(); 32874 } 32875 32876 }); 32877 } else if (interpolateValueFn) { 32878 // The value attribute is interpolated 32879 optionAttrs.$observe('value', function valueAttributeObserveAction(newVal) { 32880 // This method is overwritten in ngOptions and has side-effects! 32881 self.readValue(); 32882 32883 var removal; 32884 var previouslySelected = optionElement.prop('selected'); 32885 32886 if (isDefined(oldVal)) { 32887 self.removeOption(oldVal); 32888 removal = true; 32889 } 32890 oldVal = newVal; 32891 self.addOption(newVal, optionElement); 32892 32893 if (removal && previouslySelected) { 32894 scheduleViewValueUpdate(); 32895 } 32896 }); 32897 } else if (interpolateTextFn) { 32898 // The text content is interpolated 32899 optionScope.$watch(interpolateTextFn, function interpolateWatchAction(newVal, oldVal) { 32900 optionAttrs.$set('value', newVal); 32901 var previouslySelected = optionElement.prop('selected'); 32902 if (oldVal !== newVal) { 32903 self.removeOption(oldVal); 32904 } 32905 self.addOption(newVal, optionElement); 32906 32907 if (oldVal && previouslySelected) { 32908 scheduleViewValueUpdate(); 32909 } 32910 }); 32911 } else { 32912 // The value attribute is static 32913 self.addOption(optionAttrs.value, optionElement); 32914 } 32915 32916 32917 optionAttrs.$observe('disabled', function(newVal) { 32918 32919 // Since model updates will also select disabled options (like ngOptions), 32920 // we only have to handle options becoming disabled, not enabled 32921 32922 if (newVal === 'true' || newVal && optionElement.prop('selected')) { 32923 if (self.multiple) { 32924 scheduleViewValueUpdate(true); 32925 } else { 32926 self.ngModelCtrl.$setViewValue(null); 32927 self.ngModelCtrl.$render(); 32928 } 32929 } 32930 }); 32931 32932 optionElement.on('$destroy', function() { 32933 var currentValue = self.readValue(); 32934 var removeValue = optionAttrs.value; 32935 32936 self.removeOption(removeValue); 32937 scheduleRender(); 32938 32939 if (self.multiple && currentValue && currentValue.indexOf(removeValue) !== -1 || 32940 currentValue === removeValue 32941 ) { 32942 // When multiple (selected) options are destroyed at the same time, we don't want 32943 // to run a model update for each of them. Instead, run a single update in the $$postDigest 32944 scheduleViewValueUpdate(true); 32945 } 32946 }); 32947 }; 32948}]; 32949 32950/** 32951 * @ngdoc directive 32952 * @name select 32953 * @restrict E 32954 * 32955 * @description 32956 * HTML `select` element with angular data-binding. 32957 * 32958 * The `select` directive is used together with {@link ngModel `ngModel`} to provide data-binding 32959 * between the scope and the `<select>` control (including setting default values). 32960 * It also handles dynamic `<option>` elements, which can be added using the {@link ngRepeat `ngRepeat}` or 32961 * {@link ngOptions `ngOptions`} directives. 32962 * 32963 * When an item in the `<select>` menu is selected, the value of the selected option will be bound 32964 * to the model identified by the `ngModel` directive. With static or repeated o
32964ptions, this is 32965 * the content of the `value` attribute or the textContent of the `<option>`, if the value attribute is missing. 32966 * Value and textContent can be interpolated. 32967 * 32968 * The {@link select.SelectController select controller} exposes utility functions that can be used 32969 * to manipulate the select's behavior. 32970 * 32971 * ## Matching model and option values 32972 * 32973 * In general, the match between the model and an option is evaluated by strictly comparing the model 32974 * value against the value of the available options. 32975 * 32976 * If you are setting the option value with the option's `value` attribute, or textContent, the 32977 * value will always be a `string` which means that the model value must also be a string. 32978 * Otherwise the `select` directive cannot match them correctly. 32979 * 32980 * To bind the model to a non-string value, you can use one of the following strategies: 32981 * - the {@link ng.ngOptions `ngOptions`} directive 32982 * ({@link ng.select#using-select-with-ngoptions-and-setting-a-default-value}) 32983 * - the {@link ng.ngValue `ngValue`} directive, which allows arbitrary expressions to be 32984 * option values ({@link ng.select#using-ngvalue-to-bind-the-model-to-an-array-of-objects Example}) 32985 * - model $parsers / $formatters to convert the string value 32986 * ({@link ng.select#binding-select-to-a-non-string-value-via-ngmodel-parsing-formatting Example}) 32987 * 32988 * If the viewValue of `ngModel` does not match any of the options, then the control 32989 * will automatically add an "unknown" option, which it then removes when the mismatch is resolved. 32990 * 32991 * Optionally, a single hard-coded `<option>` element, with the value set to an empty string, can 32992 * be nested into the `<select>` element. This element will then represent the `null` or "not selected" 32993 * option. See example below for demonstration. 32994 * 32995 * ## Choosing between `ngRepeat` and `ngOptions` 32996 * 32997 * In many cases, `ngRepeat` can be used on `<option>` elements instead of {@link ng.directive:ngOptions 32998 * ngOptions} to achieve a similar result. However, `ngOptions` provides some benefits: 32999 * - more flexibility in how the `<select>`'s model is assigned via the `select` **`as`** part of the 33000 * comprehension expression 33001 * - reduced memory consumption by not creating a new scope for each repeated instance 33002 * - increased render speed by creating the options in a documentFragment instead of individually 33003 * 33004 * Specifically, select with repeated options slows down significantly starting at 2000 options in 33005 * Chrome and Internet Explorer / Edge. 33006 * 33007 * 33008 * @param {string} ngModel Assignable angular expression to data-bind to. 33009 * @param {string=} name Property name of the form under which the control is published. 33010 * @param {string=} multiple Allows multiple options to be selected. The selected values will be 33011 * bound to the model as an array. 33012 * @param {string=} required Sets `required` validation error key if the value is not entered. 33013 * @param {string=} ngRequired Adds required attribute and required validation constraint to 33014 * the element when the ngRequired expression evaluates to true. Use ngRequired instead of required 33015 * when you want to data-bind to the required attribute. 33016 * @param {string=} ngChange Angular expression to be executed when selected option(s) changes due to user 33017 * interaction with the select element. 33018 * @param {string=} ngOptions sets the options that the select is populated with and defines what is 33019 * set on the model on selection. See {@link ngOptions `ngOptions`}. 33020 * @param {string=} ngAttrSize sets the size of the select element dynamically. Uses the 33021 * {@link guide/interpolation#-ngattr-for-binding-to-arbitrary-attributes ngAttr} directive. 33022 * 33023 * 33024 * @knownIssue 33025 * 33026 * In Firefox, the select model is only updated when the select element is blurred. For example, 33027 * when switching between options with the keyboard, the select model is only set to the 33028 * currently selected option when the select is blurred, e.g via tab key or clicking the mouse 33029 * outside the select. 33030 * 33031 * This is due to an ambiguity in the select element specification. See the 33032 * [issue on the Firefox bug tracker](https://bugzilla.mozilla.org/show_bug.cgi?id=126379) 33033 * for more information, and this 33034 * [Github comment for a workaround](https://github.com/angular/angular.js/issues/9134#issuecomment-130800488) 33035 * 33036 * @example 33037 * ### Simple `select` elements with static options 33038 * 33039 * <example name="static-select" module="staticSelect"> 33040 * <file name="index.html">
33041 * <div ng-controller="ExampleController"> 33042 * <form name="myForm"> 33043 * <label for="singleSelect"> Single select: </label><br> 33044 * <select name="singleSelect" ng-model="data.singleSelect"> 33045 * <option value="option-1">Option 1</option> 33046 * <option value="option-2">Option 2</option> 33047 * </select><br> 33048 * 33049 * <label for="singleSelect"> Single select with "not selected" option and dynamic option values: </label><br> 33050 * <select name="singleSelect" id="singleSelect" ng-model="data.singleSelect"> 33051 * <option value="">---Please select---</option> <!-- not selected / blank option --> 33052 * <option value="{{data.option1}}">Option 1</option> <!-- interpolation --> 33053 * <option value="option-2">Option 2</option> 33054 * </select><br> 33055 * <button ng-click="forceUnknownOption()">Force unknown option</button><br> 33056 * <tt>singleSelect = {{data.singleSelect}}</tt> 33057 * 33058 * <hr> 33059 * <label for="multipleSelect"> Multiple select: </label><br> 33060 * <select name="multipleSelect" id="multipleSelect" ng-model="data.multipleSelect" multiple> 33061 * <option value="option-1">Option 1</option> 33062 * <option value="option-2">Option 2</option> 33063 * <option value="option-3">Option 3</option> 33064 * </select><br> 33065 * <tt>multipleSelect = {{data.multipleSelect}}</tt><br/> 33066 * </form> 33067 * </div> 33068 * </file> 33069 * <file name="app.js"> 33070 * angular.module('staticSelect', []) 33071 * .controller('ExampleController', ['$scope', function($scope) { 33072 * $scope.data = { 33073 * singleSelect: null, 33074 * multipleSelect: [], 33075 * option1: 'option-1' 33076 * }; 33077 * 33078 * $scope.forceUnknownOption = function() { 33079 * $scope.data.singleSelect = 'nonsense'; 33080 * }; 33081 * }]); 33082 * </file> 33083 *</example> 33084 * 33085 * ### Using `ngRepeat` to generate `select` options 33086 * <example name="select-ngrepeat" module="ngrepeatSelect"> 33087 * <file name="index.html">
33088 * <div ng-controller="ExampleController"> 33089 * <form name="myForm"> 33090 * <label for="repeatSelect"> Repeat select: </label> 33091 * <select name="repeatSelect" id="repeatSelect" ng-model="data.model"> 33092 * <option ng-repeat="option in data.availableOptions" value="{{option.id}}">{{option.name}}</option> 33093 * </select> 33094 * </form> 33095 * <hr> 33096 * <tt>model = {{data.model}}</tt><br/> 33097 * </div> 33098 * </file> 33099 * <file name="app.js"> 33100 * angular.module('ngrepeatSelect', []) 33101 * .controller('ExampleController', ['$scope', function($scope) { 33102 * $scope.data = { 33103 * model: null, 33104 * availableOptions: [ 33105 * {id: '1', name: 'Option A'}, 33106 * {id: '2', name: 'Option B'}, 33107 * {id: '3', name: 'Option C'} 33108 * ] 33109 * }; 33110 * }]); 33111 * </file> 33112 *</example> 33113 * 33114 * ### Using `ngValue` to bind the model to an array of objects 33115 * <example name="select-ngvalue" module="ngvalueSelect"> 33116 * <file name="index.html"> 33117 * <div ng-controller="ExampleController"> 33118 * <form name="myForm"> 33119 * <label for="ngvalueselect"> ngvalue select: </label> 33120 * <select size="6" name="ngvalueselect" ng-model="data.model" multiple> 33121 * <option ng-repeat="option in data.availableOptions" ng-value="option.value">{{option.name}}</option> 33122 * </select> 33123 * </form> 33124 * <hr> 33125 * <pre>model = {{data.model | json}}</pre><br/> 33126 * </div> 33127 * </file> 33128 * <file name="app.js"> 33129 * angular.module('ngvalueSelect', []) 33130 * .controller('ExampleController', ['$scope', function($scope) { 33131 * $scope.data = { 33132 * model: null, 33133 * availableOptions: [ 33134 {value: 'myString', name: 'string'}, 33135 {value: 1, name: 'integer'}, 33136 {value: true, name: 'boolean'}, 33137 {value: null, name: 'null'}, 33138 {value: {prop: 'value'}, name: 'object'}, 33139 {value: ['a'], name: 'array'} 33140 * ] 33141 * }; 33142 * }]); 33143 * </file> 33144 *</example> 33145 * 33146 * ### Using `select` with `ngOptions` and setting a default value 33147 * See the {@link ngOptions ngOptions documentation} for more `ngOptions` usage examples. 33148 * 33149 * <example name="select-with-default-values" module="defaultValueSelect"> 33150 * <file name="index.html">
33151 * <div ng-controller="ExampleController"> 33152 * <form name="myForm"> 33153 * <label for="mySelect">Make a choice:</label> 33154 * <select name="mySelect" id="mySelect" 33155 * ng-options="option.name for option in data.availableOptions track by option.id" 33156 * ng-model="data.selectedOption"></select> 33157 * </form> 33158 * <hr> 33159 * <tt>option = {{data.selectedOption}}</tt><br/> 33160 * </div> 33161 * </file> 33162 * <file name="app.js"> 33163 * angular.module('defaultValueSelect', []) 33164 * .controller('ExampleController', ['$scope', function($scope) { 33165 * $scope.data = { 33166 * availableOptions: [ 33167 * {id: '1', name: 'Option A'}, 33168 * {id: '2', name: 'Option B'}, 33169 * {id: '3', name: 'Option C'} 33170 * ], 33171 * selectedOption: {id: '3', name: 'Option C'} //This sets the default value of the select in the ui 33172 * }; 33173 * }]); 33174 * </file> 33175 *</example> 33176 * 33177 * 33178 * ### Binding `select` to a non-string value via `ngModel` parsing / formatting 33179 * 33180 * <example name="select-with-non-string-options" module="nonStringSelect"> 33181 * <file name="index.html"> 33182 * <select ng-model="model.id" convert-to-number> 33183 * <option value="0">Zero</option> 33184 * <option value="1">One</option> 33185 * <option value="2">Two</option> 33186 * </select> 33187 * {{ model }} 33188 * </file> 33189 * <file name="app.js"> 33190 * angular.module('nonStringSelect', []) 33191 * .run(function($rootScope) { 33192 * $rootScope.model = { id: 2 }; 33193 * }) 33194 * .directive('convertToNumber', function() { 33195 * return { 33196 * require: 'ngModel', 33197 * link: function(scope, element, attrs, ngModel) { 33198 * ngModel.$parsers.push(function(val) { 33199 * return parseInt(val, 10); 33200 * }); 33201 * ngModel.$formatters.push(function(val) { 33202 * return '' + val; 33203 * }); 33204 * } 33205 * }; 33206 * }); 33207 * </file> 33208 * <file name="protractor.js" type="protractor"> 33209 * it('should initialize to model', function() { 33210 * expect(element(by.model('model.id')).$('option:checked').getText()).toEqual('Two'); 33211 * }); 33212 * </file> 33213 * </example> 33214 * 33215 */ 33216var selectDirective = function() { 33217 33218 return { 33219 restrict: 'E', 33220 require: ['select', '?ngModel'], 33221 controller: SelectController, 33222 priority: 1, 33223 link: { 33224 pre: selectPreLink, 33225 post: selectPostLink 33226 } 33227 }; 33228 33229 function selectPreLink(scope, element, attr, ctrls) { 33230 33231 var selectCtrl = ctrls[0]; 33232 var ngModelCtrl = ctrls[1]; 33233 33234 // if ngModel is not defined, we don't need to do anything but set the registerOption 33235 // function to noop, so options don't get added internally 33236 if (!ngModelCtrl) { 33237 selectCtrl.registerOption = noop; 33238 return; 33239 } 33240 33241 33242 selectCtrl.ngModelCtrl = ngModelCtrl; 33243 33244 // When the selected item(s) changes we delegate getting the value of the select control 33245 // to the `readValue` method, which can be changed if the select can have multiple 33246 // selected values or if the options are being generated by `ngOptions` 33247 element.on('change', function() { 33248 selectCtrl.removeUnknownOption(); 33249 scope.$apply(function() { 33250 ngModelCtrl.$setViewValue(selectCtrl.readValue()); 33251 }); 33252 }); 33253 33254 // If the select allows multiple values then we need to modify how we read and write 33255 // values from and to the control; also what it means for the value to be empty and 33256 // we have to add an extra watch since ngModel doesn't work well with arrays - it 33257 // doesn't trigger rendering if only an item in the array changes. 33258 if (attr.multiple) { 33259 selectCtrl.multiple = true; 33260 33261 // Read value now needs to check each option to see if it is selected 33262 selectCtrl.readValue = function readMultipleValue() { 33263 var array = []; 33264 forEach(element.find('option'), function(option) { 33265 if (option.selected && !option.disabled) { 33266 var val = option.value; 33267 array.push(val in selectCtrl.selectValueMap ? selectCtrl.selectValueMap[val] : val); 33268 } 33269 }); 33270 return array; 33271 }; 33272 33273 // Write value now needs to set the selected property of each matching option 33274 selectCtrl.writeValue = function writeMultipleValue(value) {
vendor: 5,087 bytes, lines 33275-33392
33275 forEach(element.find('option'), function(option) { 33276 var shouldBeSelected = !!value && (includes(value, option.value) || 33277 includes(value, selectCtrl.selectValueMap[option.value])); 33278 var currentlySelected = option.selected; 33279 33280 // Support: IE 9-11 only, Edge 12-15+ 33281 // In IE and Edge adding options to the selection via shift+click/UP/DOWN 33282 // will de-select already selected options if "selected" on those options was set 33283 // more than once (i.e. when the options were already selected) 33284 // So we only modify the selected property if necessary. 33285 // Note: this behavior cannot be replicated via unit tests because it only shows in the 33286 // actual user interface. 33287 if (shouldBeSelected !== currentlySelected) { 33288 setOptionSelectedStatus(jqLite(option), shouldBeSelected); 33289 } 33290 33291 }); 33292 }; 33293 33294 // we have to do it on each watch since ngModel watches reference, but 33295 // we need to work of an array, so we need to see if anything was inserted/removed 33296 var lastView, lastViewRef = NaN; 33297 scope.$watch(function selectMultipleWatch() { 33298 if (lastViewRef === ngModelCtrl.$viewValue && !equals(lastView, ngModelCtrl.$viewValue)) { 33299 lastView = shallowCopy(ngModelCtrl.$viewValue); 33300 ngModelCtrl.$render(); 33301 } 33302 lastViewRef = ngModelCtrl.$viewValue; 33303 }); 33304 33305 // If we are a multiple select then value is now a collection 33306 // so the meaning of $isEmpty changes 33307 ngModelCtrl.$isEmpty = function(value) { 33308 return !value || value.length === 0; 33309 }; 33310 33311 } 33312 } 33313 33314 function selectPostLink(scope, element, attrs, ctrls) { 33315 // if ngModel is not defined, we don't need to do anything 33316 var ngModelCtrl = ctrls[1]; 33317 if (!ngModelCtrl) return; 33318 33319 var selectCtrl = ctrls[0]; 33320 33321 // We delegate rendering to the `writeValue` method, which can be changed 33322 // if the select can have multiple selected values or if the options are being 33323 // generated by `ngOptions`. 33324 // This must be done in the postLink fn to prevent $render to be called before 33325 // all nodes have been linked correctly. 33326 ngModelCtrl.$render = function() { 33327 selectCtrl.writeValue(ngModelCtrl.$viewValue); 33328 }; 33329 } 33330}; 33331 33332 33333// The option directive is purely designed to communicate the existence (or lack of) 33334// of dynamically created (and destroyed) option elements to their containing select 33335// directive via its controller. 33336var optionDirective = ['$interpolate', function($interpolate) { 33337 return { 33338 restrict: 'E', 33339 priority: 100, 33340 compile: function(element, attr) { 33341 var interpolateValueFn, interpolateTextFn; 33342 33343 if (isDefined(attr.ngValue)) { 33344 // Will be handled by registerOption 33345 } else if (isDefined(attr.value)) { 33346 // If the value attribute is defined, check if it contains an interpolation 33347 interpolateValueFn = $interpolate(attr.value, true); 33348 } else { 33349 // If the value attribute is not defined then we fall back to the 33350 // text content of the option element, which may be interpolated 33351 interpolateTextFn = $interpolate(element.text(), true); 33352 if (!interpolateTextFn) { 33353 attr.$set('value', element.text()); 33354 } 33355 } 33356 33357 return function(scope, element, attr) { 33358 // This is an optimization over using ^^ since we don't want to have to search 33359 // all the way to the root of the DOM for every single option element 33360 var selectCtrlName = '$selectController', 33361 parent = element.parent(), 33362 selectCtrl = parent.data(selectCtrlName) || 33363 parent.parent().data(selectCtrlName); // in case we are in optgroup 33364 33365 if (selectCtrl) { 33366 selectCtrl.registerOption(scope, element, attr, interpolateValueFn, interpolateTextFn); 33367 } 33368 }; 33369 } 33370 }; 33371}]; 33372 33373/** 33374 * @ngdoc directive 33375 * @name ngRequired 33376 * @restrict A 33377 * 33378 * @description 33379 * 33380 * ngRequired adds the required {@link ngModel.NgModelController#$validators `validator`} to {@link ngModel `ngModel`}. 33381 * It is most often used for {@link input `input`} and {@link select `select`} controls, but can also be 33382 * applied to custom controls. 33383 * 33384 * The directive sets the `required` attribute on the element if the Angular expression inside 33385 * `ngRequired` evaluates to true. A special directive for setting `required` is necessary because we 33386 * cannot use interpolation inside `required`. See the {@link guide/interpolation interpolation guide} 33387 * for more info. 33388 * 33389 * The validator will set the `required` error key to true if the `required` attribute is set and 33390 * calling {@link ngModel.NgModelController#$isEmpty `NgModelController.$isEmpty`} with the 33391 * {@link ngModel.NgModelController#$viewValue `ngModel.$viewValue`} returns `true`. For example, the 33392 * `$isEmpty()` implementation for `input[text]` checks the length of the `$viewValue`. When developing
33393 * custom controls, `$isEmpty()` can be overwritten to account for a $viewValue that is not string-based. 33394 * 33395 * @example 33396 * <example name="ngRequiredDirective" module="ngRequiredExample"> 33397 * <file name="index.html"> 33398 * <script> 33399 * angular.module('ngRequiredExample', []) 33400 * .controller('ExampleController', ['$scope', function($scope) { 33401 * $scope.required = true; 33402 * }]); 33403 * </script> 33404 * <div ng-controller="ExampleController"> 33405 * <form name="form"> 33406 * <label for="required">Toggle required: </label> 33407 * <input type="checkbox" ng-model="required" id="required" /> 33408 * <br> 33409 * <label for="input">This input must be filled if `required` is true: </label> 33410 * <input type="text" ng-model="model" id="input" name="input" ng-required="required" /><br> 33411 * <hr> 33412 * required error set? = <code>{{form.input.$error.required}}</code><br> 33413 * model = <code>{{model}}</code> 33414 * </form> 33415 * </div> 33416 * </file> 33417 * <file name="protractor.js" type="protractor"> 33418 var required = element(by.binding('form.input.$error.required')); 33419 var model = element(by.binding('model')); 33420 var input = element(by.id('input')); 33421 33422 it('should set the required error', function() { 33423 expect(required.getText()).toContain('true'); 33424 33425 input.sendKeys('123'); 33426 expect(required.getText()).not.toContain('true'); 33427 expect(model.getText()).toContain('123'); 33428 }); 33429 * </file> 33430 * </example> 33431 */ 33432var requiredDirective = function() { 33433 return { 33434 restrict: 'A', 33435 require: '?ngModel', 33436 link: function(scope, elm, attr, ctrl) { 33437 if (!ctrl) return; 33438 attr.required = true; // force truthy in case we are on non input element 33439 33440 ctrl.$validators.required = function(modelValue, viewValue) { 33441 return !attr.required || !ctrl.$isEmpty(viewValue); 33442 }; 33443 33444 attr.$observe('required', function() { 33445 ctrl.$validate(); 33446 }); 33447 } 33448 }; 33449}; 33450 33451/** 33452 * @ngdoc directive 33453 * @name ngPattern 33454 * 33455 * @description 33456 * 33457 * ngPattern adds the pattern {@link ngModel.NgModelController#$validators `validator`} to {@link ngModel `ngModel`}. 33458 * It is most often used for text-based {@link input `input`} controls, but can also be applied to custom text-based controls. 33459 * 33460 * The validator sets the `pattern` error key if the {@link ngModel.NgModelController#$viewValue `ngModel.$viewValue`} 33461 * does not match a RegExp which is obtained by evaluating the Angular expression given in the 33462 * `ngPattern` attribute value: 33463 * * If the expression evaluates to a RegExp object, then this is used directly. 33464 * * If the expression evaluates to a string, then it will be converted to a RegExp after wrapping it 33465 * in `^` and `$` characters. For instance, `"abc"` will be converted to `new RegExp('^abc$')`. 33466 * 33467 * <div class="alert alert-info"> 33468 * **Note:** Avoid using the `g` flag on the RegExp, as it will cause each successive search to 33469 * start at the index of the last search's match, thus not taking the whole input value into 33470 * account. 33471 * </div> 33472 * 33473 * <div class="alert alert-info"> 33474 * **Note:** This directive is also added when the plain `pattern` attribute is used, with two 33475 * differences: 33476 * <ol> 33477 * <li> 33478 * `ngPattern` does not set the `pattern` attribute and therefore HTML5 constraint validation is 33479 * not available. 33480 * </li> 33481 * <li> 33482 * The `ngPattern` attribute must be an expression, while the `pattern` value must be 33483 * interpolated. 33484 * </li> 33485 * </ol> 33486 * </div> 33487 * 33488 * @example 33489 * <example name="ngPatternDirective" module="ngPatternExample"> 33490 * <file name="index.html"> 33491 * <script> 33492 * angular.module('ngPatternExample', []) 33493 * .controller('ExampleController', ['$scope', function($scope) { 33494 * $scope.regex = '\\d+'; 33495 * }]); 33496 * </script>
33497 * <div ng-controller="ExampleController"> 33498 * <form name="form"> 33499 * <label for="regex">Set a pattern (regex string): </label> 33500 * <input type="text" ng-model="regex" id="regex" /> 33501 * <br> 33502 * <label for="input">This input is restricted by the current pattern: </label> 33503 * <input type="text" ng-model="model" id="input" name="input" ng-pattern="regex" /><br> 33504 * <hr> 33505 * input valid? = <code>{{form.input.$valid}}</code><br> 33506 * model = <code>{{model}}</code> 33507 * </form> 33508 * </div> 33509 * </file> 33510 * <file name="protractor.js" type="protractor"> 33511 var model = element(by.binding('model')); 33512 var input = element(by.id('input')); 33513 33514 it('should validate the input with the default pattern', function() { 33515 input.sendKeys('aaa'); 33516 expect(model.getText()).not.toContain('aaa'); 33517 33518 input.clear().then(function() { 33519 input.sendKeys('123'); 33520 expect(model.getText()).toContain('123'); 33521 }); 33522 }); 33523 * </file> 33524 * </example> 33525 */ 33526var patternDirective = function() { 33527 return { 33528 restrict: 'A', 33529 require: '?ngModel', 33530 link: function(scope, elm, attr, ctrl) { 33531 if (!ctrl) return; 33532 33533 var regexp, patternExp = attr.ngPattern || attr.pattern; 33534 attr.$observe('pattern', function(regex) { 33535 if (isString(regex) && regex.length > 0) { 33536 regex = new RegExp('^' + regex + '$'); 33537 } 33538 33539 if (regex && !regex.test) { 33540 throw minErr('ngPattern')('noregexp', 33541 'Expected {0} to be a RegExp but was {1}. Element: {2}', patternExp, 33542 regex, startingTag(elm)); 33543 } 33544 33545 regexp = regex || undefined; 33546 ctrl.$validate(); 33547 }); 33548 33549 ctrl.$validators.pattern = function(modelValue, viewValue) { 33550 // HTML5 pattern constraint validates the input value, so we validate the viewValue 33551 return ctrl.$isEmpty(viewValue) || isUndefined(regexp) || regexp.test(viewValue); 33552 }; 33553 } 33554 }; 33555}; 33556 33557/** 33558 * @ngdoc directive 33559 * @name ngMaxlength 33560 * 33561 * @description 33562 * 33563 * ngMaxlength adds the maxlength {@link ngModel.NgModelController#$validators `validator`} to {@link ngModel `ngModel`}. 33564 * It is most often used for text-based {@link input `input`} controls, but can also be applied to custom text-based controls. 33565 * 33566 * The validator sets the `maxlength` error key if the {@link ngModel.NgModelController#$viewValue `ngModel.$viewValue`} 33567 * is longer than the integer obtained by evaluating the Angular expression given in the 33568 * `ngMaxlength` attribute value. 33569 * 33570 * <div class="alert alert-info"> 33571 * **Note:** This directive is also added when the plain `maxlength` attribute is used, with two 33572 * differences: 33573 * <ol> 33574 * <li> 33575 * `ngMaxlength` does not set the `maxlength` attribute and therefore HTML5 constraint 33576 * validation is not available. 33577 * </li> 33578 * <li> 33579 * The `ngMaxlength` attribute must be an expression, while the `maxlength` value must be 33580 * interpolated. 33581 * </li> 33582 * </ol> 33583 * </div> 33584 * 33585 * @example 33586 * <example name="ngMaxlengthDirective" module="ngMaxlengthExample"> 33587 * <file name="index.html"> 33588 * <script> 33589 * angular.module('ngMaxlengthExample', []) 33590 * .controller('ExampleController', ['$scope', function($scope) { 33591 * $scope.maxlength = 5; 33592 * }]); 33593 * </script>
33594 * <div ng-controller="ExampleController"> 33595 * <form name="form"> 33596 * <label for="maxlength">Set a maxlength: </label> 33597 * <input type="number" ng-model="maxlength" id="maxlength" /> 33598 * <br> 33599 * <label for="input">This input is restricted by the current maxlength: </label> 33600 * <input type="text" ng-model="model" id="input" name="input" ng-maxlength="maxlength" /><br> 33601 * <hr> 33602 * input valid? = <code>{{form.input.$valid}}</code><br> 33603 * model = <code>{{model}}</code> 33604 * </form> 33605 * </div> 33606 * </file> 33607 * <file name="protractor.js" type="protractor"> 33608 var model = element(by.binding('model')); 33609 var input = element(by.id('input')); 33610 33611 it('should validate the input with the default maxlength', function() { 33612 input.sendKeys('abcdef'); 33613 expect(model.getText()).not.toContain('abcdef'); 33614 33615 input.clear().then(function() { 33616 input.sendKeys('abcde'); 33617 expect(model.getText()).toContain('abcde'); 33618 }); 33619 }); 33620 * </file> 33621 * </example> 33622 */ 33623var maxlengthDirective = function() { 33624 return { 33625 restrict: 'A', 33626 require: '?ngModel', 33627 link: function(scope, elm, attr, ctrl) { 33628 if (!ctrl) return; 33629 33630 var maxlength = -1; 33631 attr.$observe('maxlength', function(value) { 33632 var intVal = toInt(value); 33633 maxlength = isNumberNaN(intVal) ? -1 : intVal; 33634 ctrl.$validate(); 33635 }); 33636 ctrl.$validators.maxlength = function(modelValue, viewValue) { 33637 return (maxlength < 0) || ctrl.$isEmpty(viewValue) || (viewValue.length <= maxlength); 33638 }; 33639 } 33640 }; 33641}; 33642 33643/** 33644 * @ngdoc directive 33645 * @name ngMinlength 33646 * 33647 * @description 33648 * 33649 * ngMinlength adds the minlength {@link ngModel.NgModelController#$validators `validator`} to {@link ngModel `ngModel`}. 33650 * It is most often used for text-based {@link input `input`} controls, but can also be applied to custom text-based controls. 33651 * 33652 * The validator sets the `minlength` error key if the {@link ngModel.NgModelController#$viewValue `ngModel.$viewValue`} 33653 * is shorter than the integer obtained by evaluating the Angular expression given in the 33654 * `ngMinlength` attribute value. 33655 * 33656 * <div class="alert alert-info"> 33657 * **Note:** This directive is also added when the plain `minlength` attribute is used, with two 33658 * differences: 33659 * <ol> 33660 * <li> 33661 * `ngMinlength` does not set the `minlength` attribute and therefore HTML5 constraint 33662 * validation is not available. 33663 * </li> 33664 * <li> 33665 * The `ngMinlength` value must be an expression, while the `minlength` value must be 33666 * interpolated. 33667 * </li> 33668 * </ol> 33669 * </div> 33670 * 33671 * @example 33672 * <example name="ngMinlengthDirective" module="ngMinlengthExample"> 33673 * <file name="index.html"> 33674 * <script> 33675 * angular.module('ngMinlengthExample', []) 33676 * .controller('ExampleController', ['$scope', function($scope) { 33677 * $scope.minlength = 3; 33678 * }]); 33679 * </script>
33680 * <div ng-controller="ExampleController"> 33681 * <form name="form"> 33682 * <label for="minlength">Set a minlength: </label> 33683 * <input type="number" ng-model="minlength" id="minlength" /> 33684 * <br> 33685 * <label for="input">This input is restricted by the current minlength: </label> 33686 * <input type="text" ng-model="model" id="input" name="input" ng-minlength="minlength" /><br> 33687 * <hr> 33688 * input valid? = <code>{{form.input.$valid}}</code><br> 33689 * model = <code>{{model}}</code> 33690 * </form> 33691 * </div> 33692 * </file> 33693 * <file name="protractor.js" type="protractor"> 33694 var model = element(by.binding('model')); 33695 var input = element(by.id('input')); 33696 33697 it('should validate the input with the default minlength', function() { 33698 input.sendKeys('ab'); 33699 expect(model.getText()).not.toContain('ab'); 33700 33701 input.sendKeys('abc'); 33702 expect(model.getText()).toContain('abc'); 33703 }); 33704 * </file> 33705 * </example> 33706 */ 33707var minlengthDirective = function() { 33708 return { 33709 restrict: 'A', 33710 require: '?ngModel', 33711 link: function(scope, elm, attr, ctrl) { 33712 if (!ctrl) return; 33713 33714 var minlength = 0; 33715 attr.$observe('minlength', function(value) { 33716 minlength = toInt(value) || 0; 33717 ctrl.$validate(); 33718 }); 33719 ctrl.$validators.minlength = function(modelValue, viewValue) { 33720 return ctrl.$isEmpty(viewValue) || viewValue.length >= minlength; 33721 }; 33722 } 33723 }; 33724}; 33725 33726if (window.angular.bootstrap) { 33727 // AngularJS is already loaded, so we can return here... 33728 if (window.console) { 33729 console.log('WARNING: Tried to load angular more than once.'); 33730 } 33731 return; 33732} 33733 33734// try to bind to jquery now so that one can write jqLite(fn) 33735// but we will rebind on bootstrap again. 33736bindJQuery(); 33737 33738publishExternalAPI(angular); 33739 33740angular.module("ngLocale", [], ["$provide", function($provide) { 33741var PLURAL_CATEGORY = {ZERO: "zero", ONE: "one", TWO: "two", FEW: "few", MANY: "many", OTHER: "other"}; 33742function getDecimals(n) { 33743 n = n + ''; 33744 var i = n.indexOf('.'); 33745 return (i == -1) ? 0 : n.length - i - 1; 33746} 33747 33748function getVF(n, opt_precision) { 33749 var v = opt_precision; 33750 33751 if (undefined === v) { 33752 v = Math.min(getDecimals(n), 3); 33753 } 33754 33755 var base = Math.pow(10, v); 33756 var f = ((n * base) | 0) % base; 33757 return {v: v, f: f}; 33758} 33759 33760$provide.value("$locale", { 33761 "DATETIME_FORMATS": { 33762 "AMPMS": [ 33763 "AM", 33764 "PM" 33765 ], 33766 "DAY": [ 33767 "Sunday", 33768 "Monday", 33769 "Tuesday", 33770 "Wednesday", 33771 "Thursday", 33772 "Friday", 33773 "Saturday" 33774 ], 33775 "ERANAMES": [ 33776 "Before Christ", 33777 "Anno Domini" 33778 ], 33779 "ERAS": [ 33780 "BC", 33781 "AD" 33782 ], 33783 "FIRSTDAYOFWEEK": 6, 33784 "MONTH": [ 33785 "January", 33786 "February", 33787 "March", 33788 "April", 33789 "May", 33790 "June", 33791 "July", 33792 "August", 33793 "September", 33794 "October", 33795 "November", 33796 "December" 33797 ], 33798 "SHORTDAY": [ 33799 "Sun", 33800 "Mon", 33801 "Tue", 33802 "Wed", 33803 "Thu", 33804 "Fri", 33805 "Sat" 33806 ], 33807 "SHORTMONTH": [ 33808 "Jan", 33809 "Feb", 33810 "Mar", 33811 "Apr", 33812 "May", 33813 "Jun", 33814 "Jul", 33815 "Aug", 33816 "Sep", 33817 "Oct", 33818 "Nov", 33819 "Dec" 33820 ], 33821 "STANDALONEMONTH": [ 33822 "January", 33823 "February", 33824 "March", 33825 "April", 33826 "May", 33827 "June", 33828 "July", 33829 "August", 33830 "September", 33831 "October", 33832 "November", 33833 "December" 33834 ], 33835 "WEEKENDRANGE": [ 33836 5, 33837 6 33838 ], 33839 "fullDate": "EEEE, MMMM d, y", 33840 "longDate": "MMMM d, y", 33841 "medium": "MMM d, y h:mm:ss a", 33842 "mediumDate": "MMM d, y", 33843 "mediumTime": "h:mm:ss a", 33844 "short": "M/d/yy h:mm a", 33845 "shortDate": "M/d/yy", 33846 "shortTime": "h:mm a" 33847 }, 33848 "NUMBER_FORMATS": { 33849 "CURRENCY_SYM": "$", 33850 "DECIMAL_SEP": ".", 33851 "GROUP_SEP": ",", 33852 "PATTERNS": [ 33853 { 33854 "gSize": 3, 33855 "lgSize": 3, 33856 "maxFrac": 3, 33857 "minFrac": 0, 33858 "minInt": 1, 33859 "negPre": "-", 33860 "negSuf": "", 33861 "posPre": "", 33862 "posSuf": "" 33863 }, 33864 { 33865 "gSize": 3, 33866 "lgSize": 3, 33867 "maxFrac": 2, 33868 "minFrac": 2, 33869 "minInt": 1, 33870 "negPre": "-\u00a4", 33871 "negSuf": "", 33872 "posPre": "\u00a4", 33873 "posSuf": "" 33874 } 33875 ] 33876 }, 33877 "id": "en-us", 33878 "localeID": "en_US", 33879 "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;} 33880}); 33881}]); 33882 33883 jqLite(function() { 33884 angularInit(window.document, bootstrap); 33885 }); 33886 33887})(window); 33888 33889!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.