PageRenderTime 139ms CodeModel.GetById 18ms RepoModel.GetById 2ms app.codeStats 0ms

/src/ng/compile.js

https://github.com/IngageStroliaC/angular.js
JavaScript | 2000 lines | 966 code | 185 blank | 849 comment | 261 complexity | 304fcfce82cca232fee11f723b8de5dd MD5 | raw file
Possible License(s): JSON

Large files files are truncated, but you can click here to view the full file

  1. 'use strict';
  2. /* ! VARIABLE/FUNCTION NAMING CONVENTIONS THAT APPLY TO THIS FILE!
  3. *
  4. * DOM-related variables:
  5. *
  6. * - "node" - DOM Node
  7. * - "element" - DOM Element or Node
  8. * - "$node" or "$element" - jqLite-wrapped node or element
  9. *
  10. *
  11. * Compiler related stuff:
  12. *
  13. * - "linkFn" - linking fn of a single directive
  14. * - "nodeLinkFn" - function that aggregates all linking fns for a particular node
  15. * - "childLinkFn" - function that aggregates all linking fns for child nodes of a particular node
  16. * - "compositeLinkFn" - function that aggregates all linking fns for a compilation root (nodeList)
  17. */
  18. /**
  19. * @ngdoc function
  20. * @name ng.$compile
  21. * @function
  22. *
  23. * @description
  24. * Compiles a piece of HTML string or DOM into a template and produces a template function, which
  25. * can then be used to link {@link ng.$rootScope.Scope `scope`} and the template together.
  26. *
  27. * The compilation is a process of walking the DOM tree and matching DOM elements to
  28. * {@link ng.$compileProvider#methods_directive directives}.
  29. *
  30. * <div class="alert alert-warning">
  31. * **Note:** This document is an in-depth reference of all directive options.
  32. * For a gentle introduction to directives with examples of common use cases,
  33. * see the {@link guide/directive directive guide}.
  34. * </div>
  35. *
  36. * ## Comprehensive Directive API
  37. *
  38. * There are many different options for a directive.
  39. *
  40. * The difference resides in the return value of the factory function.
  41. * You can either return a "Directive Definition Object" (see below) that defines the directive properties,
  42. * or just the `postLink` function (all other properties will have the default values).
  43. *
  44. * <div class="alert alert-success">
  45. * **Best Practice:** It's recommended to use the "directive definition object" form.
  46. * </div>
  47. *
  48. * Here's an example directive declared with a Directive Definition Object:
  49. *
  50. * <pre>
  51. * var myModule = angular.module(...);
  52. *
  53. * myModule.directive('directiveName', function factory(injectables) {
  54. * var directiveDefinitionObject = {
  55. * priority: 0,
  56. * template: '<div></div>', // or // function(tElement, tAttrs) { ... },
  57. * // or
  58. * // templateUrl: 'directive.html', // or // function(tElement, tAttrs) { ... },
  59. * replace: false,
  60. * transclude: false,
  61. * restrict: 'A',
  62. * scope: false,
  63. * controller: function($scope, $element, $attrs, $transclude, otherInjectables) { ... },
  64. * require: 'siblingDirectiveName', // or // ['^parentDirectiveName', '?optionalDirectiveName', '?^optionalParent'],
  65. * compile: function compile(tElement, tAttrs, transclude) {
  66. * return {
  67. * pre: function preLink(scope, iElement, iAttrs, controller) { ... },
  68. * post: function postLink(scope, iElement, iAttrs, controller) { ... }
  69. * }
  70. * // or
  71. * // return function postLink( ... ) { ... }
  72. * },
  73. * // or
  74. * // link: {
  75. * // pre: function preLink(scope, iElement, iAttrs, controller) { ... },
  76. * // post: function postLink(scope, iElement, iAttrs, controller) { ... }
  77. * // }
  78. * // or
  79. * // link: function postLink( ... ) { ... }
  80. * };
  81. * return directiveDefinitionObject;
  82. * });
  83. * </pre>
  84. *
  85. * <div class="alert alert-warning">
  86. * **Note:** Any unspecified options will use the default value. You can see the default values below.
  87. * </div>
  88. *
  89. * Therefore the above can be simplified as:
  90. *
  91. * <pre>
  92. * var myModule = angular.module(...);
  93. *
  94. * myModule.directive('directiveName', function factory(injectables) {
  95. * var directiveDefinitionObject = {
  96. * link: function postLink(scope, iElement, iAttrs) { ... }
  97. * };
  98. * return directiveDefinitionObject;
  99. * // or
  100. * // return function postLink(scope, iElement, iAttrs) { ... }
  101. * });
  102. * </pre>
  103. *
  104. *
  105. *
  106. * ### Directive Definition Object
  107. *
  108. * The directive definition object provides instructions to the {@link api/ng.$compile
  109. * compiler}. The attributes are:
  110. *
  111. * #### `priority`
  112. * When there are multiple directives defined on a single DOM element, sometimes it
  113. * is necessary to specify the order in which the directives are applied. The `priority` is used
  114. * to sort the directives before their `compile` functions get called. Priority is defined as a
  115. * number. Directives with greater numerical `priority` are compiled first. Pre-link functions
  116. * are also run in priority order, but post-link functions are run in reverse order. The order
  117. * of directives with the same priority is undefined. The default priority is `0`.
  118. *
  119. * #### `terminal`
  120. * If set to true then the current `priority` will be the last set of directives
  121. * which will execute (any directives at the current priority will still execute
  122. * as the order of execution on same `priority` is undefined).
  123. *
  124. * #### `scope`
  125. * **If set to `true`,** then a new scope will be created for this directive. If multiple directives on the
  126. * same element request a new scope, only one new scope is created. The new scope rule does not
  127. * apply for the root of the template since the root of the template always gets a new scope.
  128. *
  129. * **If set to `{}` (object hash),** then a new "isolate" scope is created. The 'isolate' scope differs from
  130. * normal scope in that it does not prototypically inherit from the parent scope. This is useful
  131. * when creating reusable components, which should not accidentally read or modify data in the
  132. * parent scope.
  133. *
  134. * The 'isolate' scope takes an object hash which defines a set of local scope properties
  135. * derived from the parent scope. These local properties are useful for aliasing values for
  136. * templates. Locals definition is a hash of local scope property to its source:
  137. *
  138. * * `@` or `@attr` - bind a local scope property to the value of DOM attribute. The result is
  139. * always a string since DOM attributes are strings. If no `attr` name is specified then the
  140. * attribute name is assumed to be the same as the local name.
  141. * Given `<widget my-attr="hello {{name}}">` and widget definition
  142. * of `scope: { localName:'@myAttr' }`, then widget scope property `localName` will reflect
  143. * the interpolated value of `hello {{name}}`. As the `name` attribute changes so will the
  144. * `localName` property on the widget scope. The `name` is read from the parent scope (not
  145. * component scope).
  146. *
  147. * * `=` or `=attr` - set up bi-directional binding between a local scope property and the
  148. * parent scope property of name defined via the value of the `attr` attribute. If no `attr`
  149. * name is specified then the attribute name is assumed to be the same as the local name.
  150. * Given `<widget my-attr="parentModel">` and widget definition of
  151. * `scope: { localModel:'=myAttr' }`, then widget scope property `localModel` will reflect the
  152. * value of `parentModel` on the parent scope. Any changes to `parentModel` will be reflected
  153. * in `localModel` and any changes in `localModel` will reflect in `parentModel`. If the parent
  154. * scope property doesn't exist, it will throw a NON_ASSIGNABLE_MODEL_EXPRESSION exception. You
  155. * can avoid this behavior using `=?` or `=?attr` in order to flag the property as optional.
  156. *
  157. * * `&` or `&attr` - provides a way to execute an expression in the context of the parent scope.
  158. * If no `attr` name is specified then the attribute name is assumed to be the same as the
  159. * local name. Given `<widget my-attr="count = count + value">` and widget definition of
  160. * `scope: { localFn:'&myAttr' }`, then isolate scope property `localFn` will point to
  161. * a function wrapper for the `count = count + value` expression. Often it's desirable to
  162. * pass data from the isolated scope via an expression and to the parent scope, this can be
  163. * done by passing a map of local variable names and values into the expression wrapper fn.
  164. * For example, if the expression is `increment(amount)` then we can specify the amount value
  165. * by calling the `localFn` as `localFn({amount: 22})`.
  166. *
  167. *
  168. *
  169. * #### `controller`
  170. * Controller constructor function. The controller is instantiated before the
  171. * pre-linking phase and it is shared with other directives (see
  172. * `require` attribute). This allows the directives to communicate with each other and augment
  173. * each other's behavior. The controller is injectable (and supports bracket notation) with the following locals:
  174. *
  175. * * `$scope` - Current scope associated with the element
  176. * * `$element` - Current element
  177. * * `$attrs` - Current attributes object for the element
  178. * * `$transclude` - A transclude linking function pre-bound to the correct transclusion scope.
  179. * The scope can be overridden by an optional first argument.
  180. * `function([scope], cloneLinkingFn)`.
  181. *
  182. *
  183. * #### `require`
  184. * Require another directive and inject its controller as the fourth argument to the linking function. The
  185. * `require` takes a string name (or array of strings) of the directive(s) to pass in. If an array is used, the
  186. * injected argument will be an array in corresponding order. If no such directive can be
  187. * found, or if the directive does not have a controller, then an error is raised. The name can be prefixed with:
  188. *
  189. * * (no prefix) - Locate the required controller on the current element. Throw an error if not found.
  190. * * `?` - Attempt to locate the required controller or pass `null` to the `link` fn if not found.
  191. * * `^` - Locate the required controller by searching the element's parents. Throw an error if not found.
  192. * * `?^` - Attempt to locate the required controller by searching the element's parents or pass `null` to the
  193. * `link` fn if not found.
  194. *
  195. *
  196. * #### `controllerAs`
  197. * Controller alias at the directive scope. An alias for the controller so it
  198. * can be referenced at the directive template. The directive needs to define a scope for this
  199. * configuration to be used. Useful in the case when directive is used as component.
  200. *
  201. *
  202. * #### `restrict`
  203. * String of subset of `EACM` which restricts the directive to a specific directive
  204. * declaration style. If omitted, the default (attributes only) is used.
  205. *
  206. * * `E` - Element name: `<my-directive></my-directive>`
  207. * * `A` - Attribute (default): `<div my-directive="exp"></div>`
  208. * * `C` - Class: `<div class="my-directive: exp;"></div>`
  209. * * `M` - Comment: `<!-- directive: my-directive exp -->`
  210. *
  211. *
  212. * #### `template`
  213. * replace the current element with the contents of the HTML. The replacement process
  214. * migrates all of the attributes / classes from the old element to the new one. See the
  215. * {@link guide/directive#creating-custom-directives_creating-directives_template-expanding-directive
  216. * Directives Guide} for an example.
  217. *
  218. * You can specify `template` as a string representing the template or as a function which takes
  219. * two arguments `tElement` and `tAttrs` (described in the `compile` function api below) and
  220. * returns a string value representing the template.
  221. *
  222. *
  223. * #### `templateUrl`
  224. * Same as `template` but the template is loaded from the specified URL. Because
  225. * the template loading is asynchronous the compilation/linking is suspended until the template
  226. * is loaded.
  227. *
  228. * You can specify `templateUrl` as a string representing the URL or as a function which takes two
  229. * arguments `tElement` and `tAttrs` (described in the `compile` function api below) and returns
  230. * a string value representing the url. In either case, the template URL is passed through {@link
  231. * api/ng.$sce#methods_getTrustedResourceUrl $sce.getTrustedResourceUrl}.
  232. *
  233. *
  234. * #### `replace`
  235. * specify where the template should be inserted. Defaults to `false`.
  236. *
  237. * * `true` - the template will replace the current element.
  238. * * `false` - the template will replace the contents of the current element.
  239. *
  240. *
  241. * #### `transclude`
  242. * compile the content of the element and make it available to the directive.
  243. * Typically used with {@link api/ng.directive:ngTransclude
  244. * ngTransclude}. The advantage of transclusion is that the linking function receives a
  245. * transclusion function which is pre-bound to the correct scope. In a typical setup the widget
  246. * creates an `isolate` scope, but the transclusion is not a child, but a sibling of the `isolate`
  247. * scope. This makes it possible for the widget to have private state, and the transclusion to
  248. * be bound to the parent (pre-`isolate`) scope.
  249. *
  250. * * `true` - transclude the content of the directive.
  251. * * `'element'` - transclude the whole element including any directives defined at lower priority.
  252. *
  253. *
  254. * #### `compile`
  255. *
  256. * <pre>
  257. * function compile(tElement, tAttrs, transclude) { ... }
  258. * </pre>
  259. *
  260. * The compile function deals with transforming the template DOM. Since most directives do not do
  261. * template transformation, it is not used often. Examples that require compile functions are
  262. * directives that transform template DOM, such as {@link
  263. * api/ng.directive:ngRepeat ngRepeat}, or load the contents
  264. * asynchronously, such as {@link api/ngRoute.directive:ngView ngView}. The
  265. * compile function takes the following arguments.
  266. *
  267. * * `tElement` - template element - The element where the directive has been declared. It is
  268. * safe to do template transformation on the element and child elements only.
  269. *
  270. * * `tAttrs` - template attributes - Normalized list of attributes declared on this element shared
  271. * between all directive compile functions.
  272. *
  273. * * `transclude` - [*DEPRECATED*!] A transclude linking function: `function(scope, cloneLinkingFn)`
  274. *
  275. * <div class="alert alert-warning">
  276. * **Note:** The template instance and the link instance may be different objects if the template has
  277. * been cloned. For this reason it is **not** safe to do anything other than DOM transformations that
  278. * apply to all cloned DOM nodes within the compile function. Specifically, DOM listener registration
  279. * should be done in a linking function rather than in a compile function.
  280. * </div>
  281. *
  282. * <div class="alert alert-error">
  283. * **Note:** The `transclude` function that is passed to the compile function is deprecated, as it
  284. * e.g. does not know about the right outer scope. Please use the transclude function that is passed
  285. * to the link function instead.
  286. * </div>
  287. * A compile function can have a return value which can be either a function or an object.
  288. *
  289. * * returning a (post-link) function - is equivalent to registering the linking function via the
  290. * `link` property of the config object when the compile function is empty.
  291. *
  292. * * returning an object with function(s) registered via `pre` and `post` properties - allows you to
  293. * control when a linking function should be called during the linking phase. See info about
  294. * pre-linking and post-linking functions below.
  295. *
  296. *
  297. * #### `link`
  298. * This property is used only if the `compile` property is not defined.
  299. *
  300. * <pre>
  301. * function link(scope, iElement, iAttrs, controller, transcludeFn) { ... }
  302. * </pre>
  303. *
  304. * The link function is responsible for registering DOM listeners as well as updating the DOM. It is
  305. * executed after the template has been cloned. This is where most of the directive logic will be
  306. * put.
  307. *
  308. * * `scope` - {@link api/ng.$rootScope.Scope Scope} - The scope to be used by the
  309. * directive for registering {@link api/ng.$rootScope.Scope#methods_$watch watches}.
  310. *
  311. * * `iElement` - instance element - The element where the directive is to be used. It is safe to
  312. * manipulate the children of the element only in `postLink` function since the children have
  313. * already been linked.
  314. *
  315. * * `iAttrs` - instance attributes - Normalized list of attributes declared on this element shared
  316. * between all directive linking functions.
  317. *
  318. * * `controller` - a controller instance - A controller instance if at least one directive on the
  319. * element defines a controller. The controller is shared among all the directives, which allows
  320. * the directives to use the controllers as a communication channel.
  321. *
  322. * * `transcludeFn` - A transclude linking function pre-bound to the correct transclusion scope.
  323. * The scope can be overridden by an optional first argument. This is the same as the `$transclude`
  324. * parameter of directive controllers.
  325. * `function([scope], cloneLinkingFn)`.
  326. *
  327. *
  328. * #### Pre-linking function
  329. *
  330. * Executed before the child elements are linked. Not safe to do DOM transformation since the
  331. * compiler linking function will fail to locate the correct elements for linking.
  332. *
  333. * #### Post-linking function
  334. *
  335. * Executed after the child elements are linked. It is safe to do DOM transformation in the post-linking function.
  336. *
  337. * <a name="Attributes"></a>
  338. * ### Attributes
  339. *
  340. * The {@link api/ng.$compile.directive.Attributes Attributes} object - passed as a parameter in the
  341. * `link()` or `compile()` functions. It has a variety of uses.
  342. *
  343. * accessing *Normalized attribute names:*
  344. * Directives like 'ngBind' can be expressed in many ways: 'ng:bind', `data-ng-bind`, or 'x-ng-bind'.
  345. * the attributes object allows for normalized access to
  346. * the attributes.
  347. *
  348. * * *Directive inter-communication:* All directives share the same instance of the attributes
  349. * object which allows the directives to use the attributes object as inter directive
  350. * communication.
  351. *
  352. * * *Supports interpolation:* Interpolation attributes are assigned to the attribute object
  353. * allowing other directives to read the interpolated value.
  354. *
  355. * * *Observing interpolated attributes:* Use `$observe` to observe the value changes of attributes
  356. * that contain interpolation (e.g. `src="{{bar}}"`). Not only is this very efficient but it's also
  357. * the only way to easily get the actual value because during the linking phase the interpolation
  358. * hasn't been evaluated yet and so the value is at this time set to `undefined`.
  359. *
  360. * <pre>
  361. * function linkingFn(scope, elm, attrs, ctrl) {
  362. * // get the attribute value
  363. * console.log(attrs.ngModel);
  364. *
  365. * // change the attribute
  366. * attrs.$set('ngModel', 'new value');
  367. *
  368. * // observe changes to interpolated attribute
  369. * attrs.$observe('ngModel', function(value) {
  370. * console.log('ngModel has changed value to ' + value);
  371. * });
  372. * }
  373. * </pre>
  374. *
  375. * Below is an example using `$compileProvider`.
  376. *
  377. * <div class="alert alert-warning">
  378. * **Note**: Typically directives are registered with `module.directive`. The example below is
  379. * to illustrate how `$compile` works.
  380. * </div>
  381. *
  382. <doc:example module="compile">
  383. <doc:source>
  384. <script>
  385. angular.module('compile', [], function($compileProvider) {
  386. // configure new 'compile' directive by passing a directive
  387. // factory function. The factory function injects the '$compile'
  388. $compileProvider.directive('compile', function($compile) {
  389. // directive factory creates a link function
  390. return function(scope, element, attrs) {
  391. scope.$watch(
  392. function(scope) {
  393. // watch the 'compile' expression for changes
  394. return scope.$eval(attrs.compile);
  395. },
  396. function(value) {
  397. // when the 'compile' expression changes
  398. // assign it into the current DOM
  399. element.html(value);
  400. // compile the new DOM and link it to the current
  401. // scope.
  402. // NOTE: we only compile .childNodes so that
  403. // we don't get into infinite loop compiling ourselves
  404. $compile(element.contents())(scope);
  405. }
  406. );
  407. };
  408. })
  409. });
  410. function Ctrl($scope) {
  411. $scope.name = 'Angular';
  412. $scope.html = 'Hello {{name}}';
  413. }
  414. </script>
  415. <div ng-controller="Ctrl">
  416. <input ng-model="name"> <br>
  417. <textarea ng-model="html"></textarea> <br>
  418. <div compile="html"></div>
  419. </div>
  420. </doc:source>
  421. <doc:scenario>
  422. it('should auto compile', function() {
  423. expect(element('div[compile]').text()).toBe('Hello Angular');
  424. input('html').enter('{{name}}!');
  425. expect(element('div[compile]').text()).toBe('Angular!');
  426. });
  427. </doc:scenario>
  428. </doc:example>
  429. *
  430. *
  431. * @param {string|DOMElement} element Element or HTML string to compile into a template function.
  432. * @param {function(angular.Scope[, cloneAttachFn]} transclude function available to directives.
  433. * @param {number} maxPriority only apply directives lower then given priority (Only effects the
  434. * root element(s), not their children)
  435. * @returns {function(scope[, cloneAttachFn])} a link function which is used to bind template
  436. * (a DOM element/tree) to a scope. Where:
  437. *
  438. * * `scope` - A {@link ng.$rootScope.Scope Scope} to bind to.
  439. * * `cloneAttachFn` - If `cloneAttachFn` is provided, then the link function will clone the
  440. * `template` and call the `cloneAttachFn` function allowing the caller to attach the
  441. * cloned elements to the DOM document at the appropriate place. The `cloneAttachFn` is
  442. * called as: <br> `cloneAttachFn(clonedElement, scope)` where:
  443. *
  444. * * `clonedElement` - is a clone of the original `element` passed into the compiler.
  445. * * `scope` - is the current scope with which the linking function is working with.
  446. *
  447. * Calling the linking function returns the element of the template. It is either the original
  448. * element passed in, or the clone of the element if the `cloneAttachFn` is provided.
  449. *
  450. * After linking the view is not updated until after a call to $digest which typically is done by
  451. * Angular automatically.
  452. *
  453. * If you need access to the bound view, there are two ways to do it:
  454. *
  455. * - If you are not asking the linking function to clone the template, create the DOM element(s)
  456. * before you send them to the compiler and keep this reference around.
  457. * <pre>
  458. * var element = $compile('<p>{{total}}</p>')(scope);
  459. * </pre>
  460. *
  461. * - if on the other hand, you need the element to be cloned, the view reference from the original
  462. * example would not point to the clone, but rather to the original template that was cloned. In
  463. * this case, you can access the clone via the cloneAttachFn:
  464. * <pre>
  465. * var templateElement = angular.element('<p>{{total}}</p>'),
  466. * scope = ....;
  467. *
  468. * var clonedElement = $compile(templateElement)(scope, function(clonedElement, scope) {
  469. * //attach the clone to DOM document at the right place
  470. * });
  471. *
  472. * //now we have reference to the cloned DOM via `clonedElement`
  473. * </pre>
  474. *
  475. *
  476. * For information on how the compiler works, see the
  477. * {@link guide/compiler Angular HTML Compiler} section of the Developer Guide.
  478. */
  479. var $compileMinErr = minErr('$compile');
  480. /**
  481. * @ngdoc service
  482. * @name ng.$compileProvider
  483. * @function
  484. *
  485. * @description
  486. */
  487. $CompileProvider.$inject = ['$provide', '$$sanitizeUriProvider'];
  488. function $CompileProvider($provide, $$sanitizeUriProvider) {
  489. var hasDirectives = {},
  490. Suffix = 'Directive',
  491. COMMENT_DIRECTIVE_REGEXP = /^\s*directive\:\s*([\d\w\-_]+)\s+(.*)$/,
  492. CLASS_DIRECTIVE_REGEXP = /(([\d\w\-_]+)(?:\:([^;]+))?;?)/;
  493. // Ref: http://developers.whatwg.org/webappapis.html#event-handler-idl-attributes
  494. // The assumption is that future DOM event attribute names will begin with
  495. // 'on' and be composed of only English letters.
  496. var EVENT_HANDLER_ATTR_REGEXP = /^(on[a-z]+|formaction)$/;
  497. /**
  498. * @ngdoc function
  499. * @name ng.$compileProvider#directive
  500. * @methodOf ng.$compileProvider
  501. * @function
  502. *
  503. * @description
  504. * Register a new directive with the compiler.
  505. *
  506. * @param {string|Object} name Name of the directive in camel-case (i.e. <code>ngBind</code> which
  507. * will match as <code>ng-bind</code>), or an object map of directives where the keys are the
  508. * names and the values are the factories.
  509. * @param {function|Array} directiveFactory An injectable directive factory function. See
  510. * {@link guide/directive} for more info.
  511. * @returns {ng.$compileProvider} Self for chaining.
  512. */
  513. this.directive = function registerDirective(name, directiveFactory) {
  514. assertNotHasOwnProperty(name, 'directive');
  515. if (isString(name)) {
  516. assertArg(directiveFactory, 'directiveFactory');
  517. if (!hasDirectives.hasOwnProperty(name)) {
  518. hasDirectives[name] = [];
  519. $provide.factory(name + Suffix, ['$injector', '$exceptionHandler',
  520. function($injector, $exceptionHandler) {
  521. var directives = [];
  522. forEach(hasDirectives[name], function(directiveFactory, index) {
  523. try {
  524. var directive = $injector.invoke(directiveFactory);
  525. if (isFunction(directive)) {
  526. directive = { compile: valueFn(directive) };
  527. } else if (!directive.compile && directive.link) {
  528. directive.compile = valueFn(directive.link);
  529. }
  530. directive.priority = directive.priority || 0;
  531. directive.index = index;
  532. directive.name = directive.name || name;
  533. directive.require = directive.require || (directive.controller && directive.name);
  534. directive.restrict = directive.restrict || 'A';
  535. directives.push(directive);
  536. } catch (e) {
  537. $exceptionHandler(e);
  538. }
  539. });
  540. return directives;
  541. }]);
  542. }
  543. hasDirectives[name].push(directiveFactory);
  544. } else {
  545. forEach(name, reverseParams(registerDirective));
  546. }
  547. return this;
  548. };
  549. /**
  550. * @ngdoc function
  551. * @name ng.$compileProvider#aHrefSanitizationWhitelist
  552. * @methodOf ng.$compileProvider
  553. * @function
  554. *
  555. * @description
  556. * Retrieves or overrides the default regular expression that is used for whitelisting of safe
  557. * urls during a[href] sanitization.
  558. *
  559. * The sanitization is a security measure aimed at prevent XSS attacks via html links.
  560. *
  561. * Any url about to be assigned to a[href] via data-binding is first normalized and turned into
  562. * an absolute url. Afterwards, the url is matched against the `aHrefSanitizationWhitelist`
  563. * regular expression. If a match is found, the original url is written into the dom. Otherwise,
  564. * the absolute url is prefixed with `'unsafe:'` string and only then is it written into the DOM.
  565. *
  566. * @param {RegExp=} regexp New regexp to whitelist urls with.
  567. * @returns {RegExp|ng.$compileProvider} Current RegExp if called without value or self for
  568. * chaining otherwise.
  569. */
  570. this.aHrefSanitizationWhitelist = function(regexp) {
  571. if (isDefined(regexp)) {
  572. $$sanitizeUriProvider.aHrefSanitizationWhitelist(regexp);
  573. return this;
  574. } else {
  575. return $$sanitizeUriProvider.aHrefSanitizationWhitelist();
  576. }
  577. };
  578. /**
  579. * @ngdoc function
  580. * @name ng.$compileProvider#imgSrcSanitizationWhitelist
  581. * @methodOf ng.$compileProvider
  582. * @function
  583. *
  584. * @description
  585. * Retrieves or overrides the default regular expression that is used for whitelisting of safe
  586. * urls during img[src] sanitization.
  587. *
  588. * The sanitization is a security measure aimed at prevent XSS attacks via html links.
  589. *
  590. * Any url about to be assigned to img[src] via data-binding is first normalized and turned into
  591. * an absolute url. Afterwards, the url is matched against the `imgSrcSanitizationWhitelist`
  592. * regular expression. If a match is found, the original url is written into the dom. Otherwise,
  593. * the absolute url is prefixed with `'unsafe:'` string and only then is it written into the DOM.
  594. *
  595. * @param {RegExp=} regexp New regexp to whitelist urls with.
  596. * @returns {RegExp|ng.$compileProvider} Current RegExp if called without value or self for
  597. * chaining otherwise.
  598. */
  599. this.imgSrcSanitizationWhitelist = function(regexp) {
  600. if (isDefined(regexp)) {
  601. $$sanitizeUriProvider.imgSrcSanitizationWhitelist(regexp);
  602. return this;
  603. } else {
  604. return $$sanitizeUriProvider.imgSrcSanitizationWhitelist();
  605. }
  606. };
  607. this.$get = [
  608. '$injector', '$interpolate', '$exceptionHandler', '$http', '$templateCache', '$parse',
  609. '$controller', '$rootScope', '$document', '$sce', '$animate', '$$sanitizeUri',
  610. function($injector, $interpolate, $exceptionHandler, $http, $templateCache, $parse,
  611. $controller, $rootScope, $document, $sce, $animate, $$sanitizeUri) {
  612. var Attributes = function(element, attr) {
  613. this.$$element = element;
  614. this.$attr = attr || {};
  615. };
  616. Attributes.prototype = {
  617. $normalize: directiveNormalize,
  618. /**
  619. * @ngdoc function
  620. * @name ng.$compile.directive.Attributes#$addClass
  621. * @methodOf ng.$compile.directive.Attributes
  622. * @function
  623. *
  624. * @description
  625. * Adds the CSS class value specified by the classVal parameter to the element. If animations
  626. * are enabled then an animation will be triggered for the class addition.
  627. *
  628. * @param {string} classVal The className value that will be added to the element
  629. */
  630. $addClass : function(classVal) {
  631. if(classVal && classVal.length > 0) {
  632. $animate.addClass(this.$$element, classVal);
  633. }
  634. },
  635. /**
  636. * @ngdoc function
  637. * @name ng.$compile.directive.Attributes#$removeClass
  638. * @methodOf ng.$compile.directive.Attributes
  639. * @function
  640. *
  641. * @description
  642. * Removes the CSS class value specified by the classVal parameter from the element. If
  643. * animations are enabled then an animation will be triggered for the class removal.
  644. *
  645. * @param {string} classVal The className value that will be removed from the element
  646. */
  647. $removeClass : function(classVal) {
  648. if(classVal && classVal.length > 0) {
  649. $animate.removeClass(this.$$element, classVal);
  650. }
  651. },
  652. /**
  653. * @ngdoc function
  654. * @name ng.$compile.directive.Attributes#$updateClass
  655. * @methodOf ng.$compile.directive.Attributes
  656. * @function
  657. *
  658. * @description
  659. * Adds and removes the appropriate CSS class values to the element based on the difference
  660. * between the new and old CSS class values (specified as newClasses and oldClasses).
  661. *
  662. * @param {string} newClasses The current CSS className value
  663. * @param {string} oldClasses The former CSS className value
  664. */
  665. $updateClass : function(newClasses, oldClasses) {
  666. this.$removeClass(tokenDifference(oldClasses, newClasses));
  667. this.$addClass(tokenDifference(newClasses, oldClasses));
  668. },
  669. /**
  670. * Set a normalized attribute on the element in a way such that all directives
  671. * can share the attribute. This function properly handles boolean attributes.
  672. * @param {string} key Normalized key. (ie ngAttribute)
  673. * @param {string|boolean} value The value to set. If `null` attribute will be deleted.
  674. * @param {boolean=} writeAttr If false, does not write the value to DOM element attribute.
  675. * Defaults to true.
  676. * @param {string=} attrName Optional none normalized name. Defaults to key.
  677. */
  678. $set: function(key, value, writeAttr, attrName) {
  679. // TODO: decide whether or not to throw an error if "class"
  680. //is set through this function since it may cause $updateClass to
  681. //become unstable.
  682. var booleanKey = getBooleanAttrName(this.$$element[0], key),
  683. normalizedVal,
  684. nodeName;
  685. if (booleanKey) {
  686. this.$$element.prop(key, value);
  687. attrName = booleanKey;
  688. }
  689. this[key] = value;
  690. // translate normalized key to actual key
  691. if (attrName) {
  692. this.$attr[key] = attrName;
  693. } else {
  694. attrName = this.$attr[key];
  695. if (!attrName) {
  696. this.$attr[key] = attrName = snake_case(key, '-');
  697. }
  698. }
  699. nodeName = nodeName_(this.$$element);
  700. // sanitize a[href] and img[src] values
  701. if ((nodeName === 'A' && key === 'href') ||
  702. (nodeName === 'IMG' && key === 'src')) {
  703. this[key] = value = $$sanitizeUri(value, key === 'src');
  704. }
  705. if (writeAttr !== false) {
  706. if (value === null || value === undefined) {
  707. this.$$element.removeAttr(attrName);
  708. } else {
  709. this.$$element.attr(attrName, value);
  710. }
  711. }
  712. // fire observers
  713. var $$observers = this.$$observers;
  714. $$observers && forEach($$observers[key], function(fn) {
  715. try {
  716. fn(value);
  717. } catch (e) {
  718. $exceptionHandler(e);
  719. }
  720. });
  721. },
  722. /**
  723. * @ngdoc function
  724. * @name ng.$compile.directive.Attributes#$observe
  725. * @methodOf ng.$compile.directive.Attributes
  726. * @function
  727. *
  728. * @description
  729. * Observes an interpolated attribute.
  730. *
  731. * The observer function will be invoked once during the next `$digest` following
  732. * compilation. The observer is then invoked whenever the interpolated value
  733. * changes.
  734. *
  735. * @param {string} key Normalized key. (ie ngAttribute) .
  736. * @param {function(interpolatedValue)} fn Function that will be called whenever
  737. the interpolated value of the attribute changes.
  738. * See the {@link guide/directive#Attributes Directives} guide for more info.
  739. * @returns {function()} the `fn` parameter.
  740. */
  741. $observe: function(key, fn) {
  742. var attrs = this,
  743. $$observers = (attrs.$$observers || (attrs.$$observers = {})),
  744. listeners = ($$observers[key] || ($$observers[key] = []));
  745. listeners.push(fn);
  746. $rootScope.$evalAsync(function() {
  747. if (!listeners.$$inter) {
  748. // no one registered attribute interpolation function, so lets call it manually
  749. fn(attrs[key]);
  750. }
  751. });
  752. return fn;
  753. }
  754. };
  755. var startSymbol = $interpolate.startSymbol(),
  756. endSymbol = $interpolate.endSymbol(),
  757. denormalizeTemplate = (startSymbol == '{{' || endSymbol == '}}')
  758. ? identity
  759. : function denormalizeTemplate(template) {
  760. return template.replace(/\{\{/g, startSymbol).replace(/}}/g, endSymbol);
  761. },
  762. NG_ATTR_BINDING = /^ngAttr[A-Z]/;
  763. return compile;
  764. //================================
  765. function compile($compileNodes, transcludeFn, maxPriority, ignoreDirective,
  766. previousCompileContext) {
  767. if (!($compileNodes instanceof jqLite)) {
  768. // jquery always rewraps, whereas we need to preserve the original selector so that we can
  769. // modify it.
  770. $compileNodes = jqLite($compileNodes);
  771. }
  772. // We can not compile top level text elements since text nodes can be merged and we will
  773. // not be able to attach scope data to them, so we will wrap them in <span>
  774. forEach($compileNodes, function(node, index){
  775. if (node.nodeType == 3 /* text node */ && node.nodeValue.match(/\S+/) /* non-empty */ ) {
  776. $compileNodes[index] = node = jqLite(node).wrap('<span></span>').parent()[0];
  777. }
  778. });
  779. var compositeLinkFn =
  780. compileNodes($compileNodes, transcludeFn, $compileNodes,
  781. maxPriority, ignoreDirective, previousCompileContext);
  782. safeAddClass($compileNodes, 'ng-scope');
  783. return function publicLinkFn(scope, cloneConnectFn, transcludeControllers){
  784. assertArg(scope, 'scope');
  785. // important!!: we must call our jqLite.clone() since the jQuery one is trying to be smart
  786. // and sometimes changes the structure of the DOM.
  787. var $linkNode = cloneConnectFn
  788. ? JQLitePrototype.clone.call($compileNodes) // IMPORTANT!!!
  789. : $compileNodes;
  790. forEach(transcludeControllers, function(instance, name) {
  791. $linkNode.data('$' + name + 'Controller', instance);
  792. });
  793. // Attach scope only to non-text nodes.
  794. for(var i = 0, ii = $linkNode.length; i<ii; i++) {
  795. var node = $linkNode[i],
  796. nodeType = node.nodeType;
  797. if (nodeType === 1 /* element */ || nodeType === 9 /* document */) {
  798. $linkNode.eq(i).data('$scope', scope);
  799. }
  800. }
  801. if (cloneConnectFn) cloneConnectFn($linkNode, scope);
  802. if (compositeLinkFn) compositeLinkFn(scope, $linkNode, $linkNode);
  803. return $linkNode;
  804. };
  805. }
  806. function safeAddClass($element, className) {
  807. try {
  808. $element.addClass(className);
  809. } catch(e) {
  810. // ignore, since it means that we are trying to set class on
  811. // SVG element, where class name is read-only.
  812. }
  813. }
  814. /**
  815. * Compile function matches each node in nodeList against the directives. Once all directives
  816. * for a particular node are collected their compile functions are executed. The compile
  817. * functions return values - the linking functions - are combined into a composite linking
  818. * function, which is the a linking function for the node.
  819. *
  820. * @param {NodeList} nodeList an array of nodes or NodeList to compile
  821. * @param {function(angular.Scope[, cloneAttachFn]} transcludeFn A linking function, where the
  822. * scope argument is auto-generated to the new child of the transcluded parent scope.
  823. * @param {DOMElement=} $rootElement If the nodeList is the root of the compilation tree then
  824. * the rootElement must be set the jqLite collection of the compile root. This is
  825. * needed so that the jqLite collection items can be replaced with widgets.
  826. * @param {number=} maxPriority Max directive priority.
  827. * @returns {?function} A composite linking function of all of the matched directives or null.
  828. */
  829. function compileNodes(nodeList, transcludeFn, $rootElement, maxPriority, ignoreDirective,
  830. previousCompileContext) {
  831. var linkFns = [],
  832. attrs, directives, nodeLinkFn, childNodes, childLinkFn, linkFnFound;
  833. for (var i = 0; i < nodeList.length; i++) {
  834. attrs = new Attributes();
  835. // we must always refer to nodeList[i] since the nodes can be replaced underneath us.
  836. directives = collectDirectives(nodeList[i], [], attrs, i === 0 ? maxPriority : undefined,
  837. ignoreDirective);
  838. nodeLinkFn = (directives.length)
  839. ? applyDirectivesToNode(directives, nodeList[i], attrs, transcludeFn, $rootElement,
  840. null, [], [], previousCompileContext)
  841. : null;
  842. if (nodeLinkFn && nodeLinkFn.scope) {
  843. safeAddClass(jqLite(nodeList[i]), 'ng-scope');
  844. }
  845. childLinkFn = (nodeLinkFn && nodeLinkFn.terminal ||
  846. !(childNodes = nodeList[i].childNodes) ||
  847. !childNodes.length)
  848. ? null
  849. : compileNodes(childNodes,
  850. nodeLinkFn ? nodeLinkFn.transclude : transcludeFn);
  851. linkFns.push(nodeLinkFn, childLinkFn);
  852. linkFnFound = linkFnFound || nodeLinkFn || childLinkFn;
  853. //use the previous context only for the first element in the virtual group
  854. previousCompileContext = null;
  855. }
  856. // return a linking function if we have found anything, null otherwise
  857. return linkFnFound ? compositeLinkFn : null;
  858. function compositeLinkFn(scope, nodeList, $rootElement, boundTranscludeFn) {
  859. var nodeLinkFn, childLinkFn, node, $node, childScope, childTranscludeFn, i, ii, n;
  860. // copy nodeList so that linking doesn't break due to live list updates.
  861. var nodeListLength = nodeList.length,
  862. stableNodeList = new Array(nodeListLength);
  863. for (i = 0; i < nodeListLength; i++) {
  864. stableNodeList[i] = nodeList[i];
  865. }
  866. for(i = 0, n = 0, ii = linkFns.length; i < ii; n++) {
  867. node = stableNodeList[n];
  868. nodeLinkFn = linkFns[i++];
  869. childLinkFn = linkFns[i++];
  870. $node = jqLite(node);
  871. if (nodeLinkFn) {
  872. if (nodeLinkFn.scope) {
  873. childScope = scope.$new();
  874. $node.data('$scope', childScope);
  875. } else {
  876. childScope = scope;
  877. }
  878. childTranscludeFn = nodeLinkFn.transclude;
  879. if (childTranscludeFn || (!boundTranscludeFn && transcludeFn)) {
  880. nodeLinkFn(childLinkFn, childScope, node, $rootElement,
  881. createBoundTranscludeFn(scope, childTranscludeFn || transcludeFn)
  882. );
  883. } else {
  884. nodeLinkFn(childLinkFn, childScope, node, $rootElement, boundTranscludeFn);
  885. }
  886. } else if (childLinkFn) {
  887. childLinkFn(scope, node.childNodes, undefined, boundTranscludeFn);
  888. }
  889. }
  890. }
  891. }
  892. function createBoundTranscludeFn(scope, transcludeFn) {
  893. return function boundTranscludeFn(transcludedScope, cloneFn, controllers) {
  894. var scopeCreated = false;
  895. if (!transcludedScope) {
  896. transcludedScope = scope.$new();
  897. transcludedScope.$$transcluded = true;
  898. scopeCreated = true;
  899. }
  900. var clone = transcludeFn(transcludedScope, cloneFn, controllers);
  901. if (scopeCreated) {
  902. clone.on('$destroy', bind(transcludedScope, transcludedScope.$destroy));
  903. }
  904. return clone;
  905. };
  906. }
  907. /**
  908. * Looks for directives on the given node and adds them to the directive collection which is
  909. * sorted.
  910. *
  911. * @param node Node to search.
  912. * @param directives An array to which the directives are added to. This array is sorted before
  913. * the function returns.
  914. * @param attrs The shared attrs object which is used to populate the normalized attributes.
  915. * @param {number=} maxPriority Max directive priority.
  916. */
  917. function collectDirectives(node, directives, attrs, maxPriority, ignoreDirective) {
  918. var nodeType = node.nodeType,
  919. attrsMap = attrs.$attr,
  920. match,
  921. className;
  922. switch(nodeType) {
  923. case 1: /* Element */
  924. // use the node name: <directive>
  925. addDirective(directives,
  926. directiveNormalize(nodeName_(node).toLowerCase()), 'E', maxPriority, ignoreDirective);
  927. // iterate over the attributes
  928. for (var attr, name, nName, ngAttrName, value, nAttrs = node.attributes,
  929. j = 0, jj = nAttrs && nAttrs.length; j < jj; j++) {
  930. var attrStartName = false;
  931. var attrEndName = false;
  932. attr = nAttrs[j];
  933. if (!msie || msie >= 8 || attr.specified) {
  934. name = attr.name;
  935. // support ngAttr attribute binding
  936. ngAttrName = directiveNormalize(name);
  937. if (NG_ATTR_BINDING.test(ngAttrName)) {
  938. name = snake_case(ngAttrName.substr(6), '-');
  939. }
  940. var directiveNName = ngAttrName.replace(/(Start|End)$/, '');
  941. if (ngAttrName === directiveNName + 'Start') {
  942. attrStartName = name;
  943. attrEndName = name.substr(0, name.length - 5) + 'end';
  944. name = name.substr(0, name.length - 6);
  945. }
  946. nName = directiveNormalize(name.toLowerCase());
  947. attrsMap[nName] = name;
  948. attrs[nName] = value = trim(attr.value);
  949. if (getBooleanAttrName(node, nName)) {
  950. attrs[nName] = true; // presence means true
  951. }
  952. addAttrInterpolateDirective(node, directives, value, nName);
  953. addDirective(directives, nName, 'A', maxPriority, ignoreDirective, attrStartName,
  954. attrEndName);
  955. }
  956. }
  957. // use class as directive
  958. className = node.className;
  959. if (isString(className) && className !== '') {
  960. while (match = CLASS_DIRECTIVE_REGEXP.exec(className)) {
  961. nName = directiveNormalize(match[2]);
  962. if (addDirective(directives, nName, 'C', maxPriority, ignoreDirective)) {
  963. attrs[nName] = trim(match[3]);
  964. }
  965. className = className.substr(match.index + match[0].length);
  966. }
  967. }
  968. break;
  969. case 3: /* Text Node */
  970. addTextInterpolateDirective(directives, node.nodeValue);
  971. break;
  972. case 8: /* Comment */
  973. try {
  974. match = COMMENT_DIRECTIVE_REGEXP.exec(node.nodeValue);
  975. if (match) {
  976. nName = directiveNormalize(match[1]);
  977. if (addDirective(directives, nName, 'M', maxPriority, ignoreDirective)) {
  978. attrs[nName] = trim(match[2]);
  979. }
  980. }
  981. } catch (e) {
  982. // turns out that under some circumstances IE9 throws errors when one attempts to read
  983. // comment's node value.
  984. // Just ignore it and continue. (Can't seem to reproduce in test case.)
  985. }
  986. break;
  987. }
  988. directives.sort(byPriority);
  989. return directives;
  990. }
  991. /**
  992. * Given a node with an directive-start it collects all of the siblings until it finds
  993. * directive-end.
  994. * @param node
  995. * @param attrStart
  996. * @param attrEnd
  997. * @returns {*}
  998. */
  999. function groupScan(node, attrStart, attrEnd) {
  1000. var nodes = [];
  1001. var depth = 0;
  1002. if (attrStart && node.hasAttribute && node.hasAttribute(attrStart)) {
  1003. var startNode = node;
  1004. do {
  1005. if (!node) {
  1006. throw $compileMinErr('uterdir',
  1007. "Unterminated attribute, found '{0}' but no matching '{1}' found.",
  1008. attrStart, attrEnd);
  1009. }
  1010. if (node.nodeType == 1 /** Element **/) {
  1011. if (node.hasAttribute(attrStart)) depth++;
  1012. if (node.hasAttribute(attrEnd)) depth--;
  1013. }
  1014. nodes.push(node);
  1015. node = node.nextSibling;
  1016. } while (depth > 0);
  1017. } else {
  1018. nodes.push(node);
  1019. }
  1020. return jqLite(nodes);
  1021. }
  1022. /**
  1023. * Wrapper for linking function which converts normal linking function into a grouped
  1024. * linking function.
  1025. * @param linkFn
  1026. * @param attrStart
  1027. * @param attrEnd
  1028. * @returns {Function}
  1029. */
  1030. function groupElementsLinkFnWrapper(linkFn, attrStart, attrEnd) {
  1031. return function(scope, element, attrs, controllers, transcludeFn) {
  1032. element = groupScan(element[0], attrStart, attrEnd);
  1033. return linkFn(scope, element, attrs, controllers, transcludeFn);
  1034. };
  1035. }
  1036. /**
  1037. * Once the directives have been collected, their compile functions are executed. This method
  1038. * is responsible for inlining directive templates as well as terminating the application
  1039. * of the directives if the terminal directive has been reached.
  1040. *
  1041. * @param {Array} directives Array of collected directives to execute their compile function.
  1042. * this needs to be pre-sorted by priority order.
  1043. * @param {Node} compileNode The raw DOM node to apply the compile functions to
  1044. * @param {Object} templateAttrs The shared attribute function
  1045. * @param {function(angular.Scope[, cloneAttachFn]} transcludeFn A linking function, where the
  1046. * scope argument is auto-generated to the new
  1047. * child of the transcluded parent scope.
  1048. * @param {JQLite} jqCollection If we are working on the root of the compile tree then this
  1049. * argument has the root jqLite array so that we can replace nodes
  1050. * on it.
  1051. * @param {Object=} originalReplaceDirective An optional directive that will be ignored when
  1052. * compiling the transclusion.
  1053. * @param {Array.<Function>} preLinkFns
  1054. * @param {Array.<Function>} postLinkFns
  1055. * @param {Object} previousCompileContext Context used for previous compilation of the current
  1056. * node
  1057. * @returns linkFn
  1058. */
  1059. function applyDirectivesToNode(directives, compileNode, templateAttrs, transcludeFn,
  1060. jqCollection, originalReplaceDirective, preLinkFns, postLinkFns,
  1061. previousCompileContext) {
  1062. previousCompileContext = previousCompileContext || {};
  1063. var terminalPriority = -Number.MAX_VALUE,
  1064. newScopeDirective,
  1065. controllerDirectives = previousCompileContext.controllerDirectives,
  1066. newIsolateScopeDirective = previousCompileContext.newIsolateScopeDirective,
  1067. templateDirective = previousCompileContext.templateDirective,
  1068. nonTlbTranscludeDirective = previousCompileContext.nonTlbTranscludeDirective,
  1069. hasTranscludeDirective = false,
  1070. hasElementTranscludeDirective = false,
  1071. $compileNode = templateAttrs.$$element = jqLite(compileNode),
  1072. directive,
  1073. directiveName,
  1074. $template,
  1075. replaceDirective = originalReplaceDirective,
  1076. childTranscludeFn = transcludeFn,
  1077. linkFn,
  1078. directiveValue;
  1079. // executes all directives on the current element
  1080. for(var i = 0, ii = directives.length; i < ii; i++) {
  1081. directive = directives[i];
  1082. var attrStart = directive.$$start;
  1083. var attrEnd = directive.$$end;
  1084. // collect multiblock sections
  1085. if (attrStart) {
  1086. $compileNode = groupScan(compileNode, attrStart, attrEnd);
  1087. }
  1088. $template = undefined;
  1089. if (terminalPriority > directive.priority) {
  1090. break; // prevent further processing of directives
  1091. }

Large files files are truncated, but you can click here to view the full file