PageRenderTime 55ms CodeModel.GetById 17ms RepoModel.GetById 1ms app.codeStats 0ms

/src/ng/compile.js

https://github.com/mirikle/angular.js
JavaScript | 2548 lines | 1203 code | 241 blank | 1104 comment | 330 complexity | da55ea4eab28110ce3c79b4fa25cfaff 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 service
  20. * @name $compile
  21. * @kind function
  22. *
  23. * @description
  24. * Compiles an 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#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. * ```js
  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. * transclude: false,
  60. * restrict: 'A',
  61. * templateNamespace: 'html',
  62. * scope: false,
  63. * controller: function($scope, $element, $attrs, $transclude, otherInjectables) { ... },
  64. * controllerAs: 'stringAlias',
  65. * require: 'siblingDirectiveName', // or // ['^parentDirectiveName', '?optionalDirectiveName', '?^optionalParent'],
  66. * compile: function compile(tElement, tAttrs, transclude) {
  67. * return {
  68. * pre: function preLink(scope, iElement, iAttrs, controller) { ... },
  69. * post: function postLink(scope, iElement, iAttrs, controller) { ... }
  70. * }
  71. * // or
  72. * // return function postLink( ... ) { ... }
  73. * },
  74. * // or
  75. * // link: {
  76. * // pre: function preLink(scope, iElement, iAttrs, controller) { ... },
  77. * // post: function postLink(scope, iElement, iAttrs, controller) { ... }
  78. * // }
  79. * // or
  80. * // link: function postLink( ... ) { ... }
  81. * };
  82. * return directiveDefinitionObject;
  83. * });
  84. * ```
  85. *
  86. * <div class="alert alert-warning">
  87. * **Note:** Any unspecified options will use the default value. You can see the default values below.
  88. * </div>
  89. *
  90. * Therefore the above can be simplified as:
  91. *
  92. * ```js
  93. * var myModule = angular.module(...);
  94. *
  95. * myModule.directive('directiveName', function factory(injectables) {
  96. * var directiveDefinitionObject = {
  97. * link: function postLink(scope, iElement, iAttrs) { ... }
  98. * };
  99. * return directiveDefinitionObject;
  100. * // or
  101. * // return function postLink(scope, iElement, iAttrs) { ... }
  102. * });
  103. * ```
  104. *
  105. *
  106. *
  107. * ### Directive Definition Object
  108. *
  109. * The directive definition object provides instructions to the {@link ng.$compile
  110. * compiler}. The attributes are:
  111. *
  112. * #### `multiElement`
  113. * When this property is set to true, the HTML compiler will collect DOM nodes between
  114. * nodes with the attributes `directive-name-start` and `directive-name-end`, and group them
  115. * together as the directive elements. It is recomended that this feature be used on directives
  116. * which are not strictly behavioural (such as {@link ngClick}), and which
  117. * do not manipulate or replace child nodes (such as {@link ngInclude}).
  118. *
  119. * #### `priority`
  120. * When there are multiple directives defined on a single DOM element, sometimes it
  121. * is necessary to specify the order in which the directives are applied. The `priority` is used
  122. * to sort the directives before their `compile` functions get called. Priority is defined as a
  123. * number. Directives with greater numerical `priority` are compiled first. Pre-link functions
  124. * are also run in priority order, but post-link functions are run in reverse order. The order
  125. * of directives with the same priority is undefined. The default priority is `0`.
  126. *
  127. * #### `terminal`
  128. * If set to true then the current `priority` will be the last set of directives
  129. * which will execute (any directives at the current priority will still execute
  130. * as the order of execution on same `priority` is undefined). Note that expressions
  131. * and other directives used in the directive's template will also be excluded from execution.
  132. *
  133. * #### `scope`
  134. * **If set to `true`,** then a new scope will be created for this directive. If multiple directives on the
  135. * same element request a new scope, only one new scope is created. The new scope rule does not
  136. * apply for the root of the template since the root of the template always gets a new scope.
  137. *
  138. * **If set to `{}` (object hash),** then a new "isolate" scope is created. The 'isolate' scope differs from
  139. * normal scope in that it does not prototypically inherit from the parent scope. This is useful
  140. * when creating reusable components, which should not accidentally read or modify data in the
  141. * parent scope.
  142. *
  143. * The 'isolate' scope takes an object hash which defines a set of local scope properties
  144. * derived from the parent scope. These local properties are useful for aliasing values for
  145. * templates. Locals definition is a hash of local scope property to its source:
  146. *
  147. * * `@` or `@attr` - bind a local scope property to the value of DOM attribute. The result is
  148. * always a string since DOM attributes are strings. If no `attr` name is specified then the
  149. * attribute name is assumed to be the same as the local name.
  150. * Given `<widget my-attr="hello {{name}}">` and widget definition
  151. * of `scope: { localName:'@myAttr' }`, then widget scope property `localName` will reflect
  152. * the interpolated value of `hello {{name}}`. As the `name` attribute changes so will the
  153. * `localName` property on the widget scope. The `name` is read from the parent scope (not
  154. * component scope).
  155. *
  156. * * `=` or `=attr` - set up bi-directional binding between a local scope property and the
  157. * parent scope property of name defined via the value of the `attr` attribute. If no `attr`
  158. * name is specified then the attribute name is assumed to be the same as the local name.
  159. * Given `<widget my-attr="parentModel">` and widget definition of
  160. * `scope: { localModel:'=myAttr' }`, then widget scope property `localModel` will reflect the
  161. * value of `parentModel` on the parent scope. Any changes to `parentModel` will be reflected
  162. * in `localModel` and any changes in `localModel` will reflect in `parentModel`. If the parent
  163. * scope property doesn't exist, it will throw a NON_ASSIGNABLE_MODEL_EXPRESSION exception. You
  164. * can avoid this behavior using `=?` or `=?attr` in order to flag the property as optional. If
  165. * you want to shallow watch for changes (i.e. $watchCollection instead of $watch) you can use
  166. * `=*` or `=*attr` (`=*?` or `=*?attr` if the property is optional).
  167. *
  168. * * `&` or `&attr` - provides a way to execute an expression in the context of the parent scope.
  169. * If no `attr` name is specified then the attribute name is assumed to be the same as the
  170. * local name. Given `<widget my-attr="count = count + value">` and widget definition of
  171. * `scope: { localFn:'&myAttr' }`, then isolate scope property `localFn` will point to
  172. * a function wrapper for the `count = count + value` expression. Often it's desirable to
  173. * pass data from the isolated scope via an expression to the parent scope, this can be
  174. * done by passing a map of local variable names and values into the expression wrapper fn.
  175. * For example, if the expression is `increment(amount)` then we can specify the amount value
  176. * by calling the `localFn` as `localFn({amount: 22})`.
  177. *
  178. *
  179. * #### `bindToController`
  180. * When an isolate scope is used for a component (see above), and `controllerAs` is used, `bindToController` will
  181. * allow a component to have its properties bound to the controller, rather than to scope. When the controller
  182. * is instantiated, the initial values of the isolate scope bindings are already available.
  183. *
  184. * #### `controller`
  185. * Controller constructor function. The controller is instantiated before the
  186. * pre-linking phase and it is shared with other directives (see
  187. * `require` attribute). This allows the directives to communicate with each other and augment
  188. * each other's behavior. The controller is injectable (and supports bracket notation) with the following locals:
  189. *
  190. * * `$scope` - Current scope associated with the element
  191. * * `$element` - Current element
  192. * * `$attrs` - Current attributes object for the element
  193. * * `$transclude` - A transclude linking function pre-bound to the correct transclusion scope:
  194. * `function([scope], cloneLinkingFn, futureParentElement)`.
  195. * * `scope`: optional argument to override the scope.
  196. * * `cloneLinkingFn`: optional argument to create clones of the original transcluded content.
  197. * * `futureParentElement`:
  198. * * defines the parent to which the `cloneLinkingFn` will add the cloned elements.
  199. * * default: `$element.parent()` resp. `$element` for `transclude:'element'` resp. `transclude:true`.
  200. * * only needed for transcludes that are allowed to contain non html elements (e.g. SVG elements)
  201. * and when the `cloneLinkinFn` is passed,
  202. * as those elements need to created and cloned in a special way when they are defined outside their
  203. * usual containers (e.g. like `<svg>`).
  204. * * See also the `directive.templateNamespace` property.
  205. *
  206. *
  207. * #### `require`
  208. * Require another directive and inject its controller as the fourth argument to the linking function. The
  209. * `require` takes a string name (or array of strings) of the directive(s) to pass in. If an array is used, the
  210. * injected argument will be an array in corresponding order. If no such directive can be
  211. * found, or if the directive does not have a controller, then an error is raised. The name can be prefixed with:
  212. *
  213. * * (no prefix) - Locate the required controller on the current element. Throw an error if not found.
  214. * * `?` - Attempt to locate the required controller or pass `null` to the `link` fn if not found.
  215. * * `^` - Locate the required controller by searching the element and its parents. Throw an error if not found.
  216. * * `^^` - Locate the required controller by searching the element's parents. Throw an error if not found.
  217. * * `?^` - Attempt to locate the required controller by searching the element and its parents or pass
  218. * `null` to the `link` fn if not found.
  219. * * `?^^` - Attempt to locate the required controller by searching the element's parents, or pass
  220. * `null` to the `link` fn if not found.
  221. *
  222. *
  223. * #### `controllerAs`
  224. * Controller alias at the directive scope. An alias for the controller so it
  225. * can be referenced at the directive template. The directive needs to define a scope for this
  226. * configuration to be used. Useful in the case when directive is used as component.
  227. *
  228. *
  229. * #### `restrict`
  230. * String of subset of `EACM` which restricts the directive to a specific directive
  231. * declaration style. If omitted, the defaults (elements and attributes) are used.
  232. *
  233. * * `E` - Element name (default): `<my-directive></my-directive>`
  234. * * `A` - Attribute (default): `<div my-directive="exp"></div>`
  235. * * `C` - Class: `<div class="my-directive: exp;"></div>`
  236. * * `M` - Comment: `<!-- directive: my-directive exp -->`
  237. *
  238. *
  239. * #### `templateNamespace`
  240. * String representing the document type used by the markup in the template.
  241. * AngularJS needs this information as those elements need to be created and cloned
  242. * in a special way when they are defined outside their usual containers like `<svg>` and `<math>`.
  243. *
  244. * * `html` - All root nodes in the template are HTML. Root nodes may also be
  245. * top-level elements such as `<svg>` or `<math>`.
  246. * * `svg` - The root nodes in the template are SVG elements (excluding `<math>`).
  247. * * `math` - The root nodes in the template are MathML elements (excluding `<svg>`).
  248. *
  249. * If no `templateNamespace` is specified, then the namespace is considered to be `html`.
  250. *
  251. * #### `template`
  252. * HTML markup that may:
  253. * * Replace the contents of the directive's element (default).
  254. * * Replace the directive's element itself (if `replace` is true - DEPRECATED).
  255. * * Wrap the contents of the directive's element (if `transclude` is true).
  256. *
  257. * Value may be:
  258. *
  259. * * A string. For example `<div red-on-hover>{{delete_str}}</div>`.
  260. * * A function which takes two arguments `tElement` and `tAttrs` (described in the `compile`
  261. * function api below) and returns a string value.
  262. *
  263. *
  264. * #### `templateUrl`
  265. * This is similar to `template` but the template is loaded from the specified URL, asynchronously.
  266. *
  267. * Because template loading is asynchronous the compiler will suspend compilation of directives on that element
  268. * for later when the template has been resolved. In the meantime it will continue to compile and link
  269. * sibling and parent elements as though this element had not contained any directives.
  270. *
  271. * The compiler does not suspend the entire compilation to wait for templates to be loaded because this
  272. * would result in the whole app "stalling" until all templates are loaded asynchronously - even in the
  273. * case when only one deeply nested directive has `templateUrl`.
  274. *
  275. * Template loading is asynchronous even if the template has been preloaded into the {@link $templateCache}
  276. *
  277. * You can specify `templateUrl` as a string representing the URL or as a function which takes two
  278. * arguments `tElement` and `tAttrs` (described in the `compile` function api below) and returns
  279. * a string value representing the url. In either case, the template URL is passed through {@link
  280. * $sce#getTrustedResourceUrl $sce.getTrustedResourceUrl}.
  281. *
  282. *
  283. * #### `replace` ([*DEPRECATED*!], will be removed in next major release - i.e. v2.0)
  284. * specify what the template should replace. Defaults to `false`.
  285. *
  286. * * `true` - the template will replace the directive's element.
  287. * * `false` - the template will replace the contents of the directive's element.
  288. *
  289. * The replacement process migrates all of the attributes / classes from the old element to the new
  290. * one. See the {@link guide/directive#template-expanding-directive
  291. * Directives Guide} for an example.
  292. *
  293. * There are very few scenarios where element replacement is required for the application function,
  294. * the main one being reusable custom components that are used within SVG contexts
  295. * (because SVG doesn't work with custom elements in the DOM tree).
  296. *
  297. * #### `transclude`
  298. * Extract the contents of the element where the directive appears and make it available to the directive.
  299. * The contents are compiled and provided to the directive as a **transclusion function**. See the
  300. * {@link $compile#transclusion Transclusion} section below.
  301. *
  302. * There are two kinds of transclusion depending upon whether you want to transclude just the contents of the
  303. * directive's element or the entire element:
  304. *
  305. * * `true` - transclude the content (i.e. the child nodes) of the directive's element.
  306. * * `'element'` - transclude the whole of the directive's element including any directives on this
  307. * element that defined at a lower priority than this directive. When used, the `template`
  308. * property is ignored.
  309. *
  310. *
  311. * #### `compile`
  312. *
  313. * ```js
  314. * function compile(tElement, tAttrs, transclude) { ... }
  315. * ```
  316. *
  317. * The compile function deals with transforming the template DOM. Since most directives do not do
  318. * template transformation, it is not used often. The compile function takes the following arguments:
  319. *
  320. * * `tElement` - template element - The element where the directive has been declared. It is
  321. * safe to do template transformation on the element and child elements only.
  322. *
  323. * * `tAttrs` - template attributes - Normalized list of attributes declared on this element shared
  324. * between all directive compile functions.
  325. *
  326. * * `transclude` - [*DEPRECATED*!] A transclude linking function: `function(scope, cloneLinkingFn)`
  327. *
  328. * <div class="alert alert-warning">
  329. * **Note:** The template instance and the link instance may be different objects if the template has
  330. * been cloned. For this reason it is **not** safe to do anything other than DOM transformations that
  331. * apply to all cloned DOM nodes within the compile function. Specifically, DOM listener registration
  332. * should be done in a linking function rather than in a compile function.
  333. * </div>
  334. * <div class="alert alert-warning">
  335. * **Note:** The compile function cannot handle directives that recursively use themselves in their
  336. * own templates or compile functions. Compiling these directives results in an infinite loop and a
  337. * stack overflow errors.
  338. *
  339. * This can be avoided by manually using $compile in the postLink function to imperatively compile
  340. * a directive's template instead of relying on automatic template compilation via `template` or
  341. * `templateUrl` declaration or manual compilation inside the compile function.
  342. * </div>
  343. *
  344. * <div class="alert alert-error">
  345. * **Note:** The `transclude` function that is passed to the compile function is deprecated, as it
  346. * e.g. does not know about the right outer scope. Please use the transclude function that is passed
  347. * to the link function instead.
  348. * </div>
  349. * A compile function can have a return value which can be either a function or an object.
  350. *
  351. * * returning a (post-link) function - is equivalent to registering the linking function via the
  352. * `link` property of the config object when the compile function is empty.
  353. *
  354. * * returning an object with function(s) registered via `pre` and `post` properties - allows you to
  355. * control when a linking function should be called during the linking phase. See info about
  356. * pre-linking and post-linking functions below.
  357. *
  358. *
  359. * #### `link`
  360. * This property is used only if the `compile` property is not defined.
  361. *
  362. * ```js
  363. * function link(scope, iElement, iAttrs, controller, transcludeFn) { ... }
  364. * ```
  365. *
  366. * The link function is responsible for registering DOM listeners as well as updating the DOM. It is
  367. * executed after the template has been cloned. This is where most of the directive logic will be
  368. * put.
  369. *
  370. * * `scope` - {@link ng.$rootScope.Scope Scope} - The scope to be used by the
  371. * directive for registering {@link ng.$rootScope.Scope#$watch watches}.
  372. *
  373. * * `iElement` - instance element - The element where the directive is to be used. It is safe to
  374. * manipulate the children of the element only in `postLink` function since the children have
  375. * already been linked.
  376. *
  377. * * `iAttrs` - instance attributes - Normalized list of attributes declared on this element shared
  378. * between all directive linking functions.
  379. *
  380. * * `controller` - a controller instance - A controller instance if at least one directive on the
  381. * element defines a controller. The controller is shared among all the directives, which allows
  382. * the directives to use the controllers as a communication channel.
  383. *
  384. * * `transcludeFn` - A transclude linking function pre-bound to the correct transclusion scope.
  385. * This is the same as the `$transclude`
  386. * parameter of directive controllers, see there for details.
  387. * `function([scope], cloneLinkingFn, futureParentElement)`.
  388. *
  389. * #### Pre-linking function
  390. *
  391. * Executed before the child elements are linked. Not safe to do DOM transformation since the
  392. * compiler linking function will fail to locate the correct elements for linking.
  393. *
  394. * #### Post-linking function
  395. *
  396. * Executed after the child elements are linked.
  397. *
  398. * Note that child elements that contain `templateUrl` directives will not have been compiled
  399. * and linked since they are waiting for their template to load asynchronously and their own
  400. * compilation and linking has been suspended until that occurs.
  401. *
  402. * It is safe to do DOM transformation in the post-linking function on elements that are not waiting
  403. * for their async templates to be resolved.
  404. *
  405. *
  406. * ### Transclusion
  407. *
  408. * Transclusion is the process of extracting a collection of DOM element from one part of the DOM and
  409. * copying them to another part of the DOM, while maintaining their connection to the original AngularJS
  410. * scope from where they were taken.
  411. *
  412. * Transclusion is used (often with {@link ngTransclude}) to insert the
  413. * original contents of a directive's element into a specified place in the template of the directive.
  414. * The benefit of transclusion, over simply moving the DOM elements manually, is that the transcluded
  415. * content has access to the properties on the scope from which it was taken, even if the directive
  416. * has isolated scope.
  417. * See the {@link guide/directive#creating-a-directive-that-wraps-other-elements Directives Guide}.
  418. *
  419. * This makes it possible for the widget to have private state for its template, while the transcluded
  420. * content has access to its originating scope.
  421. *
  422. * <div class="alert alert-warning">
  423. * **Note:** When testing an element transclude directive you must not place the directive at the root of the
  424. * DOM fragment that is being compiled. See {@link guide/unit-testing#testing-transclusion-directives
  425. * Testing Transclusion Directives}.
  426. * </div>
  427. *
  428. * #### Transclusion Functions
  429. *
  430. * When a directive requests transclusion, the compiler extracts its contents and provides a **transclusion
  431. * function** to the directive's `link` function and `controller`. This transclusion function is a special
  432. * **linking function** that will return the compiled contents linked to a new transclusion scope.
  433. *
  434. * <div class="alert alert-info">
  435. * If you are just using {@link ngTransclude} then you don't need to worry about this function, since
  436. * ngTransclude will deal with it for us.
  437. * </div>
  438. *
  439. * If you want to manually control the insertion and removal of the transcluded content in your directive
  440. * then you must use this transclude function. When you call a transclude function it returns a a jqLite/JQuery
  441. * object that contains the compiled DOM, which is linked to the correct transclusion scope.
  442. *
  443. * When you call a transclusion function you can pass in a **clone attach function**. This function accepts
  444. * two parameters, `function(clone, scope) { ... }`, where the `clone` is a fresh compiled copy of your transcluded
  445. * content and the `scope` is the newly created transclusion scope, to which the clone is bound.
  446. *
  447. * <div class="alert alert-info">
  448. * **Best Practice**: Always provide a `cloneFn` (clone attach function) when you call a translude function
  449. * since you then get a fresh clone of the original DOM and also have access to the new transclusion scope.
  450. * </div>
  451. *
  452. * It is normal practice to attach your transcluded content (`clone`) to the DOM inside your **clone
  453. * attach function**:
  454. *
  455. * ```js
  456. * var transcludedContent, transclusionScope;
  457. *
  458. * $transclude(function(clone, scope) {
  459. * element.append(clone);
  460. * transcludedContent = clone;
  461. * transclusionScope = scope;
  462. * });
  463. * ```
  464. *
  465. * Later, if you want to remove the transcluded content from your DOM then you should also destroy the
  466. * associated transclusion scope:
  467. *
  468. * ```js
  469. * transcludedContent.remove();
  470. * transclusionScope.$destroy();
  471. * ```
  472. *
  473. * <div class="alert alert-info">
  474. * **Best Practice**: if you intend to add and remove transcluded content manually in your directive
  475. * (by calling the transclude function to get the DOM and and calling `element.remove()` to remove it),
  476. * then you are also responsible for calling `$destroy` on the transclusion scope.
  477. * </div>
  478. *
  479. * The built-in DOM manipulation directives, such as {@link ngIf}, {@link ngSwitch} and {@link ngRepeat}
  480. * automatically destroy their transluded clones as necessary so you do not need to worry about this if
  481. * you are simply using {@link ngTransclude} to inject the transclusion into your directive.
  482. *
  483. *
  484. * #### Transclusion Scopes
  485. *
  486. * When you call a transclude function it returns a DOM fragment that is pre-bound to a **transclusion
  487. * scope**. This scope is special, in that it is a child of the directive's scope (and so gets destroyed
  488. * when the directive's scope gets destroyed) but it inherits the properties of the scope from which it
  489. * was taken.
  490. *
  491. * For example consider a directive that uses transclusion and isolated scope. The DOM hierarchy might look
  492. * like this:
  493. *
  494. * ```html
  495. * <div ng-app>
  496. * <div isolate>
  497. * <div transclusion>
  498. * </div>
  499. * </div>
  500. * </div>
  501. * ```
  502. *
  503. * The `$parent` scope hierarchy will look like this:
  504. *
  505. * ```
  506. * - $rootScope
  507. * - isolate
  508. * - transclusion
  509. * ```
  510. *
  511. * but the scopes will inherit prototypically from different scopes to their `$parent`.
  512. *
  513. * ```
  514. * - $rootScope
  515. * - transclusion
  516. * - isolate
  517. * ```
  518. *
  519. *
  520. * ### Attributes
  521. *
  522. * The {@link ng.$compile.directive.Attributes Attributes} object - passed as a parameter in the
  523. * `link()` or `compile()` functions. It has a variety of uses.
  524. *
  525. * accessing *Normalized attribute names:*
  526. * Directives like 'ngBind' can be expressed in many ways: 'ng:bind', `data-ng-bind`, or 'x-ng-bind'.
  527. * the attributes object allows for normalized access to
  528. * the attributes.
  529. *
  530. * * *Directive inter-communication:* All directives share the same instance of the attributes
  531. * object which allows the directives to use the attributes object as inter directive
  532. * communication.
  533. *
  534. * * *Supports interpolation:* Interpolation attributes are assigned to the attribute object
  535. * allowing other directives to read the interpolated value.
  536. *
  537. * * *Observing interpolated attributes:* Use `$observe` to observe the value changes of attributes
  538. * that contain interpolation (e.g. `src="{{bar}}"`). Not only is this very efficient but it's also
  539. * the only way to easily get the actual value because during the linking phase the interpolation
  540. * hasn't been evaluated yet and so the value is at this time set to `undefined`.
  541. *
  542. * ```js
  543. * function linkingFn(scope, elm, attrs, ctrl) {
  544. * // get the attribute value
  545. * console.log(attrs.ngModel);
  546. *
  547. * // change the attribute
  548. * attrs.$set('ngModel', 'new value');
  549. *
  550. * // observe changes to interpolated attribute
  551. * attrs.$observe('ngModel', function(value) {
  552. * console.log('ngModel has changed value to ' + value);
  553. * });
  554. * }
  555. * ```
  556. *
  557. * ## Example
  558. *
  559. * <div class="alert alert-warning">
  560. * **Note**: Typically directives are registered with `module.directive`. The example below is
  561. * to illustrate how `$compile` works.
  562. * </div>
  563. *
  564. <example module="compileExample">
  565. <file name="index.html">
  566. <script>
  567. angular.module('compileExample', [], function($compileProvider) {
  568. // configure new 'compile' directive by passing a directive
  569. // factory function. The factory function injects the '$compile'
  570. $compileProvider.directive('compile', function($compile) {
  571. // directive factory creates a link function
  572. return function(scope, element, attrs) {
  573. scope.$watch(
  574. function(scope) {
  575. // watch the 'compile' expression for changes
  576. return scope.$eval(attrs.compile);
  577. },
  578. function(value) {
  579. // when the 'compile' expression changes
  580. // assign it into the current DOM
  581. element.html(value);
  582. // compile the new DOM and link it to the current
  583. // scope.
  584. // NOTE: we only compile .childNodes so that
  585. // we don't get into infinite loop compiling ourselves
  586. $compile(element.contents())(scope);
  587. }
  588. );
  589. };
  590. });
  591. })
  592. .controller('GreeterController', ['$scope', function($scope) {
  593. $scope.name = 'Angular';
  594. $scope.html = 'Hello {{name}}';
  595. }]);
  596. </script>
  597. <div ng-controller="GreeterController">
  598. <input ng-model="name"> <br>
  599. <textarea ng-model="html"></textarea> <br>
  600. <div compile="html"></div>
  601. </div>
  602. </file>
  603. <file name="protractor.js" type="protractor">
  604. it('should auto compile', function() {
  605. var textarea = $('textarea');
  606. var output = $('div[compile]');
  607. // The initial state reads 'Hello Angular'.
  608. expect(output.getText()).toBe('Hello Angular');
  609. textarea.clear();
  610. textarea.sendKeys('{{name}}!');
  611. expect(output.getText()).toBe('Angular!');
  612. });
  613. </file>
  614. </example>
  615. *
  616. *
  617. * @param {string|DOMElement} element Element or HTML string to compile into a template function.
  618. * @param {function(angular.Scope, cloneAttachFn=)} transclude function available to directives.
  619. * @param {number} maxPriority only apply directives lower than given priority (Only effects the
  620. * root element(s), not their children)
  621. * @returns {function(scope, cloneAttachFn=)} a link function which is used to bind template
  622. * (a DOM element/tree) to a scope. Where:
  623. *
  624. * * `scope` - A {@link ng.$rootScope.Scope Scope} to bind to.
  625. * * `cloneAttachFn` - If `cloneAttachFn` is provided, then the link function will clone the
  626. * `template` and call the `cloneAttachFn` function allowing the caller to attach the
  627. * cloned elements to the DOM document at the appropriate place. The `cloneAttachFn` is
  628. * called as: <br> `cloneAttachFn(clonedElement, scope)` where:
  629. *
  630. * * `clonedElement` - is a clone of the original `element` passed into the compiler.
  631. * * `scope` - is the current scope with which the linking function is working with.
  632. *
  633. * Calling the linking function returns the element of the template. It is either the original
  634. * element passed in, or the clone of the element if the `cloneAttachFn` is provided.
  635. *
  636. * After linking the view is not updated until after a call to $digest which typically is done by
  637. * Angular automatically.
  638. *
  639. * If you need access to the bound view, there are two ways to do it:
  640. *
  641. * - If you are not asking the linking function to clone the template, create the DOM element(s)
  642. * before you send them to the compiler and keep this reference around.
  643. * ```js
  644. * var element = $compile('<p>{{total}}</p>')(scope);
  645. * ```
  646. *
  647. * - if on the other hand, you need the element to be cloned, the view reference from the original
  648. * example would not point to the clone, but rather to the original template that was cloned. In
  649. * this case, you can access the clone via the cloneAttachFn:
  650. * ```js
  651. * var templateElement = angular.element('<p>{{total}}</p>'),
  652. * scope = ....;
  653. *
  654. * var clonedElement = $compile(templateElement)(scope, function(clonedElement, scope) {
  655. * //attach the clone to DOM document at the right place
  656. * });
  657. *
  658. * //now we have reference to the cloned DOM via `clonedElement`
  659. * ```
  660. *
  661. *
  662. * For information on how the compiler works, see the
  663. * {@link guide/compiler Angular HTML Compiler} section of the Developer Guide.
  664. */
  665. var $compileMinErr = minErr('$compile');
  666. /**
  667. * @ngdoc provider
  668. * @name $compileProvider
  669. *
  670. * @description
  671. */
  672. $CompileProvider.$inject = ['$provide', '$$sanitizeUriProvider'];
  673. function $CompileProvider($provide, $$sanitizeUriProvider) {
  674. var hasDirectives = {},
  675. Suffix = 'Directive',
  676. COMMENT_DIRECTIVE_REGEXP = /^\s*directive\:\s*([\w\-]+)\s+(.*)$/,
  677. CLASS_DIRECTIVE_REGEXP = /(([\w\-]+)(?:\:([^;]+))?;?)/,
  678. ALL_OR_NOTHING_ATTRS = makeMap('ngSrc,ngSrcset,src,srcset'),
  679. REQUIRE_PREFIX_REGEXP = /^(?:(\^\^?)?(\?)?(\^\^?)?)?/;
  680. // Ref: http://developers.whatwg.org/webappapis.html#event-handler-idl-attributes
  681. // The assumption is that future DOM event attribute names will begin with
  682. // 'on' and be composed of only English letters.
  683. var EVENT_HANDLER_ATTR_REGEXP = /^(on[a-z]+|formaction)$/;
  684. function parseIsolateBindings(scope, directiveName) {
  685. var LOCAL_REGEXP = /^\s*([@&]|=(\*?))(\??)\s*(\w*)\s*$/;
  686. var bindings = {};
  687. forEach(scope, function(definition, scopeName) {
  688. var match = definition.match(LOCAL_REGEXP);
  689. if (!match) {
  690. throw $compileMinErr('iscp',
  691. "Invalid isolate scope definition for directive '{0}'." +
  692. " Definition: {... {1}: '{2}' ...}",
  693. directiveName, scopeName, definition);
  694. }
  695. bindings[scopeName] = {
  696. mode: match[1][0],
  697. collection: match[2] === '*',
  698. optional: match[3] === '?',
  699. attrName: match[4] || scopeName
  700. };
  701. });
  702. return bindings;
  703. }
  704. /**
  705. * @ngdoc method
  706. * @name $compileProvider#directive
  707. * @kind function
  708. *
  709. * @description
  710. * Register a new directive with the compiler.
  711. *
  712. * @param {string|Object} name Name of the directive in camel-case (i.e. <code>ngBind</code> which
  713. * will match as <code>ng-bind</code>), or an object map of directives where the keys are the
  714. * names and the values are the factories.
  715. * @param {Function|Array} directiveFactory An injectable directive factory function. See
  716. * {@link guide/directive} for more info.
  717. * @returns {ng.$compileProvider} Self for chaining.
  718. */
  719. this.directive = function registerDirective(name, directiveFactory) {
  720. assertNotHasOwnProperty(name, 'directive');
  721. if (isString(name)) {
  722. assertArg(directiveFactory, 'directiveFactory');
  723. if (!hasDirectives.hasOwnProperty(name)) {
  724. hasDirectives[name] = [];
  725. $provide.factory(name + Suffix, ['$injector', '$exceptionHandler',
  726. function($injector, $exceptionHandler) {
  727. var directives = [];
  728. forEach(hasDirectives[name], function(directiveFactory, index) {
  729. try {
  730. var directive = $injector.invoke(directiveFactory);
  731. if (isFunction(directive)) {
  732. directive = { compile: valueFn(directive) };
  733. } else if (!directive.compile && directive.link) {
  734. directive.compile = valueFn(directive.link);
  735. }
  736. directive.priority = directive.priority || 0;
  737. directive.index = index;
  738. directive.name = directive.name || name;
  739. directive.require = directive.require || (directive.controller && directive.name);
  740. directive.restrict = directive.restrict || 'EA';
  741. if (isObject(directive.scope)) {
  742. directive.$$isolateBindings = parseIsolateBindings(directive.scope, directive.name);
  743. }
  744. directives.push(directive);
  745. } catch (e) {
  746. $exceptionHandler(e);
  747. }
  748. });
  749. return directives;
  750. }]);
  751. }
  752. hasDirectives[name].push(directiveFactory);
  753. } else {
  754. forEach(name, reverseParams(registerDirective));
  755. }
  756. return this;
  757. };
  758. /**
  759. * @ngdoc method
  760. * @name $compileProvider#aHrefSanitizationWhitelist
  761. * @kind function
  762. *
  763. * @description
  764. * Retrieves or overrides the default regular expression that is used for whitelisting of safe
  765. * urls during a[href] sanitization.
  766. *
  767. * The sanitization is a security measure aimed at prevent XSS attacks via html links.
  768. *
  769. * Any url about to be assigned to a[href] via data-binding is first normalized and turned into
  770. * an absolute url. Afterwards, the url is matched against the `aHrefSanitizationWhitelist`
  771. * regular expression. If a match is found, the original url is written into the dom. Otherwise,
  772. * the absolute url is prefixed with `'unsafe:'` string and only then is it written into the DOM.
  773. *
  774. * @param {RegExp=} regexp New regexp to whitelist urls with.
  775. * @returns {RegExp|ng.$compileProvider} Current RegExp if called without value or self for
  776. * chaining otherwise.
  777. */
  778. this.aHrefSanitizationWhitelist = function(regexp) {
  779. if (isDefined(regexp)) {
  780. $$sanitizeUriProvider.aHrefSanitizationWhitelist(regexp);
  781. return this;
  782. } else {
  783. return $$sanitizeUriProvider.aHrefSanitizationWhitelist();
  784. }
  785. };
  786. /**
  787. * @ngdoc method
  788. * @name $compileProvider#imgSrcSanitizationWhitelist
  789. * @kind function
  790. *
  791. * @description
  792. * Retrieves or overrides the default regular expression that is used for whitelisting of safe
  793. * urls during img[src] sanitization.
  794. *
  795. * The sanitization is a security measure aimed at prevent XSS attacks via html links.
  796. *
  797. * Any url about to be assigned to img[src] via data-binding is first normalized and turned into
  798. * an absolute url. Afterwards, the url is matched against the `imgSrcSanitizationWhitelist`
  799. * regular expression. If a match is found, the original url is written into the dom. Otherwise,
  800. * the absolute url is prefixed with `'unsafe:'` string and only then is it written into the DOM.
  801. *
  802. * @param {RegExp=} regexp New regexp to whitelist urls with.
  803. * @returns {RegExp|ng.$compileProvider} Current RegExp if called without value or self for
  804. * chaining otherwise.
  805. */
  806. this.imgSrcSanitizationWhitelist = function(regexp) {
  807. if (isDefined(regexp)) {
  808. $$sanitizeUriProvider.imgSrcSanitizationWhitelist(regexp);
  809. return this;
  810. } else {
  811. return $$sanitizeUriProvider.imgSrcSanitizationWhitelist();
  812. }
  813. };
  814. /**
  815. * @ngdoc method
  816. * @name $compileProvider#debugInfoEnabled
  817. *
  818. * @param {boolean=} enabled update the debugInfoEnabled state if provided, otherwise just return the
  819. * current debugInfoEnabled state
  820. * @returns {*} current value if used as getter or itself (chaining) if used as setter
  821. *
  822. * @kind function
  823. *
  824. * @description
  825. * Call this method to enable/disable various debug runtime information in the compiler such as adding
  826. * binding information and a reference to the current scope on to DOM elements.
  827. * If enabled, the compiler will add the following to DOM elements that have been bound to the scope
  828. * * `ng-binding` CSS class
  829. * * `$binding` data property containing an array of the binding expressions
  830. *
  831. * You may want to use this in production for a significant performance boost. See
  832. * {@link guide/production#disabling-debug-data Disabling Debug Data} for more.
  833. *
  834. * The default value is true.
  835. */
  836. var debugInfoEnabled = true;
  837. this.debugInfoEnabled = function(enabled) {
  838. if (isDefined(enabled)) {
  839. debugInfoEnabled = enabled;
  840. return this;
  841. }
  842. return debugInfoEnabled;
  843. };
  844. this.$get = [
  845. '$injector', '$interpolate', '$exceptionHandler', '$templateRequest', '$parse',
  846. '$controller', '$rootScope', '$document', '$sce', '$animate', '$$sanitizeUri',
  847. function($injector, $interpolate, $exceptionHandler, $templateRequest, $parse,
  848. $controller, $rootScope, $document, $sce, $animate, $$sanitizeUri) {
  849. var Attributes = function(element, attributesToCopy) {
  850. if (attributesToCopy) {
  851. var keys = Object.keys(attributesToCopy);
  852. var i, l, key;
  853. for (i = 0, l = keys.length; i < l; i++) {
  854. key = keys[i];
  855. this[key] = attributesToCopy[key];
  856. }
  857. } else {
  858. this.$attr = {};
  859. }
  860. this.$$element = element;
  861. };
  862. Attributes.prototype = {
  863. $normalize: directiveNormalize,
  864. /**
  865. * @ngdoc method
  866. * @name $compile.directive.Attributes#$addClass
  867. * @kind function
  868. *
  869. * @description
  870. * Adds the CSS class value specified by the classVal parameter to the element. If animations
  871. * are enabled then an animation will be triggered for the class addition.
  872. *
  873. * @param {string} classVal The className value that will be added to the element
  874. */
  875. $addClass: function(classVal) {
  876. if (classVal && classVal.length > 0) {
  877. $animate.addClass(this.$$element, classVal);
  878. }
  879. },
  880. /**
  881. * @ngdoc method
  882. * @name $compile.directive.Attributes#$removeClass
  883. * @kind function
  884. *
  885. * @description
  886. * Removes the CSS class value specified by the classVal parameter from the element. If
  887. * animations are enabled then an animation will be triggered for the class removal.
  888. *
  889. * @param {string} classVal The className value that will be removed from the element
  890. */
  891. $removeClass: function(classVal) {
  892. if (classVal && classVal.length > 0) {
  893. $animate.removeClass(this.$$element, classVal);
  894. }
  895. },
  896. /**
  897. * @ngdoc method
  898. * @name $compile.directive.Attributes#$updateClass
  899. * @kind function
  900. *
  901. * @description
  902. * Adds and removes the appropriate CSS class values to the element based on the difference
  903. * between the new and old CSS class values (specified as newClasses and oldClasses).
  904. *
  905. * @param {string} newClasses The current CSS className value
  906. * @param {string} oldClasses The former CSS className value
  907. */
  908. $updateClass: function(newClasses, oldClasses) {
  909. var toAdd = tokenDifference(newClasses, oldClasses);
  910. if (toAdd && toAdd.length) {
  911. $animate.addClass(this.$$element, toAdd);
  912. }
  913. var toRemove = tokenDifference(oldClasses, newClasses);
  914. if (toRemove && toRemove.length) {
  915. $animate.removeClass(this.$$element, toRemove);
  916. }
  917. },
  918. /**
  919. * Set a normalized attribute on the element in a way such that all directives
  920. * can share the attribute. This function properly handles boolean attributes.
  921. * @param {string} key Normalized key. (ie ngAttribute)
  922. * @param {string|boolean} value The value to set. If `null` attribute will be deleted.
  923. * @param {boolean=} writeAttr If false, does not write the value to DOM element attribute.
  924. * Defaults to true.
  925. * @param {string=} attrName Optional none normalized name. Defaults to key.
  926. */
  927. $set: function(key, value, writeAttr, attrName) {
  928. // TODO: decide whether or not to throw an error if "class"
  929. //is set through this function since it may cause $updateClass to
  930. //become unstable.
  931. var node = this.$$element[0],
  932. booleanKey = getBooleanAttrName(node, key),
  933. aliasedKey = getAliasedAttrName(node, key),
  934. observer = key,
  935. nodeName;
  936. if (booleanKey) {
  937. this.$$element.prop(key, value);
  938. attrName = booleanKey;
  939. } else if (aliasedKey) {
  940. this[aliasedKey] = value;
  941. observer = aliasedKey;
  942. }
  943. this[key] = value;
  944. // translate normalized key to actual key
  945. if (attrName) {
  946. this.$attr[key] = attrName;
  947. } else {
  948. attrName = this.$attr[key];
  949. if (!attrName) {
  950. this.$attr[key] = attrName = snake_case(key, '-');
  951. }
  952. }
  953. nodeName = nodeName_(this.$$element);
  954. if ((nodeName === 'a' && key === 'href') ||
  955. (nodeName === 'img' && key === 'src')) {
  956. // sanitize a[href] and img[src] values
  957. this[key] = value = $$sanitizeUri(value, key === 'src');
  958. } else if (nodeName === 'img' && key === 'srcset') {
  959. // sanitize img[srcset] values
  960. var result = "";
  961. // first check if there are spaces because it's not the same pattern
  962. var trimmedSrcset = trim(value);
  963. // ( 999x ,| 999w ,| ,|, )
  964. var srcPattern = /(\s+\d+x\s*,|\s+\d+w\s*,|\s+,|,\s+)/;
  965. var pattern = /\s/.test(trimmedSrcset) ? srcPattern : /(,)/;
  966. // split srcset into tuple of uri and descriptor except for the last item
  967. var rawUris = trimmedSrcset.split(pattern);
  968. // for each tuples
  969. var nbrUrisWith2parts = Math.floor(rawUris.length / 2);
  970. for (var i=0; i<nbrUrisWith2parts; i++) {
  971. var innerIdx = i*2;
  972. // sanitize the uri
  973. result += $$sanitizeUri(trim(rawUris[innerIdx]), true);
  974. // add the descriptor
  975. result += (" " + trim(rawUris[innerIdx+1]));
  976. }
  977. // split the last item into uri and descriptor
  978. var lastTuple = trim(rawUris[i*2]).split(/\s/);
  979. // sanitize the last uri
  980. result += $$sanitizeUri(trim(lastTuple[0]), true);
  981. // and add the last descriptor if any
  982. if (lastTuple.length === 2) {
  983. result += (" " + trim(lastTuple[1]));
  984. }
  985. this[key] = value = result;
  986. }
  987. if (writeAttr !== false) {
  988. if (value === null || value === undefined) {
  989. this.$$element.removeAttr(attrName);
  990. } else {
  991. this.$$element.attr(attrName, value);
  992. }
  993. }
  994. // fire observers
  995. var $$observers = this.$$observers;
  996. $$observers && forEach($$observers[observer], function(fn) {
  997. try {
  998. fn(value);
  999. } catch (e) {
  1000. $exceptionHandler(e);
  1001. }
  1002. });
  1003. },
  1004. /**
  1005. * @ngdoc method
  1006. * @name $compile.directive.Attributes#$observe
  1007. * @kind function
  1008. *
  1009. * @description
  1010. * Observes an interpolated attribute.
  1011. *
  1012. * The observer function will be invoked once during the next `$digest` following
  1013. * compilation. The observer is then invoked whenever the interpolated value
  1014. * changes.
  1015. *
  1016. * @param {string} key Normalized key. (ie ngAttribute) .
  1017. * @param {function(interpolatedValue)} fn Function that will be called whenever
  1018. the interpolated value of the attribute changes.
  1019. * See the {@link guide/directive#text-and-attribute-bindings Directives} guide for more info.
  1020. * @returns {function()} Returns a deregistration function for this observer.
  1021. */
  1022. $observe: function(key, fn) {
  1023. var attrs = this,
  1024. $$observers = (attrs.$$observers || (attrs.$$observers = createMap())),
  1025. listeners = ($$observers[key] || ($$observers[key] = []));
  1026. listeners.push(fn);
  1027. $rootScope.$evalAsync(function() {
  1028. if (!listeners.$$inter && attrs.hasOwnProperty(key)) {
  1029. // no one registered attribute interpolation function, so lets call it manually
  1030. fn(attrs[key]);
  1031. }
  1032. });
  1033. return function() {
  1034. arrayRemove(listeners, fn);
  1035. };
  1036. }
  1037. };
  1038. function safeAddClass($element, className) {
  1039. try {
  1040. $element.addClass(className);
  1041. } catch (e) {
  1042. // ignore, since it means that we are trying to set class on
  1043. // SVG element, where class name is read-only.
  1044. }
  1045. }
  1046. var startSymbol = $interpolate.startSymbol(),
  1047. endSymbol = $interpolate.endSymbol(),
  1048. denormalizeTemplate = (startSymbol == '{{' || endSymbol == '}}')
  1049. ? identity
  1050. : function denormalizeTemplate(template) {
  1051. return template.replace(/\{\{/g, startSymbol).replace(/}}/g, endSymbol);
  1052. },
  1053. NG_ATTR_BINDING = /^ngAttr[A-Z]/;
  1054. compile.$$addBindingInfo = debugInfoEnabled ? function $$addBindingInfo($element, binding) {
  1055. var bindings = $element.data('$binding') || [];
  1056. if (isArray(binding)) {
  1057. bindings = bindings.concat(binding);
  1058. } else {
  1059. bindings.push(binding);
  1060. }
  1061. $element.data('$binding', bindings);
  1062. } : noop;
  1063. compile.$$addBindingClass = debugInfoEnabled ? function $$addBindingClass($element) {
  1064. safeAddClass($element, 'ng-binding');
  1065. } : noop;
  1066. compile.$$addScopeInfo = debugInfoEnabled ? function $$addScopeInfo($element, scope, isolated, noTemplate) {
  1067. var dataName = isolated ? (noTemplate ? '$isolateScopeNoTemplate' : '$isolateScope') : '$scope';
  1068. $element.data(dataName, scope);
  1069. } : noop;
  1070. compile.$$addScopeClass = debugInfoEnabled ? function $$addScopeClass($element, isolated) {
  1071. safeAddClass($element, isolated ? 'ng-isolate-scope' : 'ng-scope');
  1072. } : noop;
  1073. return compile;
  1074. //================================
  1075. function compile($compileNodes, transcludeFn, maxPriority, ignoreDirective,
  1076. previousCompileContext) {
  1077. if (!($compileNodes instanceof jqLite)) {
  1078. // jquery always rewraps, whereas we need to preserve the original selector so that we can
  1079. // modify it.
  1080. $compileNodes = jqLite($compileNodes);
  1081. }
  1082. // We can not compile top level text elements since text nodes can be merged and we will
  1083. // not be able to attach scope data to them, so we will wrap them in <span>
  1084. forEach($compileNodes, function(node, index) {
  1085. if (node.nodeType == NODE_TYPE_TEXT && node.nodeValue.match(/\S+/) /* non-empty */ ) {
  1086. $compileNodes[index] = jqLite(node).wrap('<span></span>').parent()[0];
  1087. }
  1088. });
  1089. var compositeLinkFn =
  1090. compileNodes($compileNodes, transcludeFn, $compileNodes,

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