PageRenderTime 64ms CodeModel.GetById 19ms RepoModel.GetById 0ms app.codeStats 1ms

/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
  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,
  1091. maxPriority, ignoreDirective, previousCompileContext);
  1092. compile.$$addScopeClass($compileNodes);
  1093. var namespace = null;
  1094. return function publicLinkFn(scope, cloneConnectFn, transcludeControllers, parentBoundTranscludeFn, futureParentElement) {
  1095. assertArg(scope, 'scope');
  1096. if (!namespace) {
  1097. namespace = detectNamespaceForChildElements(futureParentElement);
  1098. }
  1099. var $linkNode;
  1100. if (namespace !== 'html') {
  1101. // When using a directive with replace:true and templateUrl the $compileNodes
  1102. // (or a child element inside of them)
  1103. // might change, so we need to recreate the namespace adapted compileNodes
  1104. // for call to the link function.
  1105. // Note: This will already clone the nodes...
  1106. $linkNode = jqLite(
  1107. wrapTemplate(namespace, jqLite('<div>').append($compileNodes).html())
  1108. );
  1109. } else if (cloneConnectFn) {
  1110. // important!!: we must call our jqLite.clone() since the jQuery one is trying to be smart
  1111. // and sometimes changes the structure of the DOM.
  1112. $linkNode = JQLitePrototype.clone.call($compileNodes);
  1113. } else {
  1114. $linkNode = $compileNodes;
  1115. }
  1116. if (transcludeControllers) {
  1117. for (var controllerName in transcludeControllers) {
  1118. $linkNode.data('$' + controllerName + 'Controller', transcludeControllers[controllerName].instance);
  1119. }
  1120. }
  1121. compile.$$addScopeInfo($linkNode, scope);
  1122. if (cloneConnectFn) cloneConnectFn($linkNode, scope);
  1123. if (compositeLinkFn) compositeLinkFn(scope, $linkNode, $linkNode, parentBoundTranscludeFn);
  1124. return $linkNode;
  1125. };
  1126. }
  1127. function detectNamespaceForChildElements(parentElement) {
  1128. // TODO: Make this detect MathML as well...
  1129. var node = parentElement && parentElement[0];
  1130. if (!node) {
  1131. return 'html';
  1132. } else {
  1133. return nodeName_(node) !== 'foreignobject' && node.toString().match(/SVG/) ? 'svg': 'html';
  1134. }
  1135. }
  1136. /**
  1137. * Compile function matches each node in nodeList against the directives. Once all directives
  1138. * for a particular node are collected their compile functions are executed. The compile
  1139. * functions return values - the linking functions - are combined into a composite linking
  1140. * function, which is the a linking function for the node.
  1141. *
  1142. * @param {NodeList} nodeList an array of nodes or NodeList to compile
  1143. * @param {function(angular.Scope, cloneAttachFn=)} transcludeFn A linking function, where the
  1144. * scope argument is auto-generated to the new child of the transcluded parent scope.
  1145. * @param {DOMElement=} $rootElement If the nodeList is the root of the compilation tree then
  1146. * the rootElement must be set the jqLite collection of the compile root. This is
  1147. * needed so that the jqLite collection items can be replaced with widgets.
  1148. * @param {number=} maxPriority Max directive priority.
  1149. * @returns {Function} A composite linking function of all of the matched directives or null.
  1150. */
  1151. function compileNodes(nodeList, transcludeFn, $rootElement, maxPriority, ignoreDirective,
  1152. previousCompileContext) {
  1153. var linkFns = [],
  1154. attrs, directives, nodeLinkFn, childNodes, childLinkFn, linkFnFound, nodeLinkFnFound;
  1155. for (var i = 0; i < nodeList.length; i++) {
  1156. attrs = new Attributes();
  1157. // we must always refer to nodeList[i] since the nodes can be replaced underneath us.
  1158. directives = collectDirectives(nodeList[i], [], attrs, i === 0 ? maxPriority : undefined,
  1159. ignoreDirective);
  1160. nodeLinkFn = (directives.length)
  1161. ? applyDirectivesToNode(directives, nodeList[i], attrs, transcludeFn, $rootElement,
  1162. null, [], [], previousCompileContext)
  1163. : null;
  1164. if (nodeLinkFn && nodeLinkFn.scope) {
  1165. compile.$$addScopeClass(attrs.$$element);
  1166. }
  1167. childLinkFn = (nodeLinkFn && nodeLinkFn.terminal ||
  1168. !(childNodes = nodeList[i].childNodes) ||
  1169. !childNodes.length)
  1170. ? null
  1171. : compileNodes(childNodes,
  1172. nodeLinkFn ? (
  1173. (nodeLinkFn.transcludeOnThisElement || !nodeLinkFn.templateOnThisElement)
  1174. && nodeLinkFn.transclude) : transcludeFn);
  1175. if (nodeLinkFn || childLinkFn) {
  1176. linkFns.push(i, nodeLinkFn, childLinkFn);
  1177. linkFnFound = true;
  1178. nodeLinkFnFound = nodeLinkFnFound || nodeLinkFn;
  1179. }
  1180. //use the previous context only for the first element in the virtual group
  1181. previousCompileContext = null;
  1182. }
  1183. // return a linking function if we have found anything, null otherwise
  1184. return linkFnFound ? compositeLinkFn : null;
  1185. function compositeLinkFn(scope, nodeList, $rootElement, parentBoundTranscludeFn) {
  1186. var nodeLinkFn, childLinkFn, node, childScope, i, ii, idx, childBoundTranscludeFn;
  1187. var stableNodeList;
  1188. if (nodeLinkFnFound) {
  1189. // copy nodeList so that if a nodeLinkFn removes or adds an element at this DOM level our
  1190. // offsets don't get screwed up
  1191. var nodeListLength = nodeList.length;
  1192. stableNodeList = new Array(nodeListLength);
  1193. // create a sparse array by only copying the elements which have a linkFn
  1194. for (i = 0; i < linkFns.length; i+=3) {
  1195. idx = linkFns[i];
  1196. stableNodeList[idx] = nodeList[idx];
  1197. }
  1198. } else {
  1199. stableNodeList = nodeList;
  1200. }
  1201. for (i = 0, ii = linkFns.length; i < ii;) {
  1202. node = stableNodeList[linkFns[i++]];
  1203. nodeLinkFn = linkFns[i++];
  1204. childLinkFn = linkFns[i++];
  1205. if (nodeLinkFn) {
  1206. if (nodeLinkFn.scope) {
  1207. childScope = scope.$new();
  1208. compile.$$addScopeInfo(jqLite(node), childScope);
  1209. } else {
  1210. childScope = scope;
  1211. }
  1212. if (nodeLinkFn.transcludeOnThisElement) {
  1213. childBoundTranscludeFn = createBoundTranscludeFn(
  1214. scope, nodeLinkFn.transclude, parentBoundTranscludeFn,
  1215. nodeLinkFn.elementTranscludeOnThisElement);
  1216. } else if (!nodeLinkFn.templateOnThisElement && parentBoundTranscludeFn) {
  1217. childBoundTranscludeFn = parentBoundTranscludeFn;
  1218. } else if (!parentBoundTranscludeFn && transcludeFn) {
  1219. childBoundTranscludeFn = createBoundTranscludeFn(scope, transcludeFn);
  1220. } else {
  1221. childBoundTranscludeFn = null;
  1222. }
  1223. nodeLinkFn(childLinkFn, childScope, node, $rootElement, childBoundTranscludeFn);
  1224. } else if (childLinkFn) {
  1225. childLinkFn(scope, node.childNodes, undefined, parentBoundTranscludeFn);
  1226. }
  1227. }
  1228. }
  1229. }
  1230. function createBoundTranscludeFn(scope, transcludeFn, previousBoundTranscludeFn, elementTransclusion) {
  1231. var boundTranscludeFn = function(transcludedScope, cloneFn, controllers, futureParentElement, containingScope) {
  1232. if (!transcludedScope) {
  1233. transcludedScope = scope.$new(false, containingScope);
  1234. transcludedScope.$$transcluded = true;
  1235. }
  1236. return transcludeFn(transcludedScope, cloneFn, controllers, previousBoundTranscludeFn, futureParentElement);
  1237. };
  1238. return boundTranscludeFn;
  1239. }
  1240. /**
  1241. * Looks for directives on the given node and adds them to the directive collection which is
  1242. * sorted.
  1243. *
  1244. * @param node Node to search.
  1245. * @param directives An array to which the directives are added to. This array is sorted before
  1246. * the function returns.
  1247. * @param attrs The shared attrs object which is used to populate the normalized attributes.
  1248. * @param {number=} maxPriority Max directive priority.
  1249. */
  1250. function collectDirectives(node, directives, attrs, maxPriority, ignoreDirective) {
  1251. var nodeType = node.nodeType,
  1252. attrsMap = attrs.$attr,
  1253. match,
  1254. className;
  1255. switch (nodeType) {
  1256. case NODE_TYPE_ELEMENT: /* Element */
  1257. // use the node name: <directive>
  1258. addDirective(directives,
  1259. directiveNormalize(nodeName_(node)), 'E', maxPriority, ignoreDirective);
  1260. // iterate over the attributes
  1261. for (var attr, name, nName, ngAttrName, value, isNgAttr, nAttrs = node.attributes,
  1262. j = 0, jj = nAttrs && nAttrs.length; j < jj; j++) {
  1263. var attrStartName = false;
  1264. var attrEndName = false;
  1265. attr = nAttrs[j];
  1266. name = attr.name;
  1267. value = trim(attr.value);
  1268. // support ngAttr attribute binding
  1269. ngAttrName = directiveNormalize(name);
  1270. if (isNgAttr = NG_ATTR_BINDING.test(ngAttrName)) {
  1271. name = snake_case(ngAttrName.substr(6), '-');
  1272. }
  1273. var directiveNName = ngAttrName.replace(/(Start|End)$/, '');
  1274. if (directiveIsMultiElement(directiveNName)) {
  1275. if (ngAttrName === directiveNName + 'Start') {
  1276. attrStartName = name;
  1277. attrEndName = name.substr(0, name.length - 5) + 'end';
  1278. name = name.substr(0, name.length - 6);
  1279. }
  1280. }
  1281. nName = directiveNormalize(name.toLowerCase());
  1282. attrsMap[nName] = name;
  1283. if (isNgAttr || !attrs.hasOwnProperty(nName)) {
  1284. attrs[nName] = value;
  1285. if (getBooleanAttrName(node, nName)) {
  1286. attrs[nName] = true; // presence means true
  1287. }
  1288. }
  1289. addAttrInterpolateDirective(node, directives, value, nName, isNgAttr);
  1290. addDirective(directives, nName, 'A', maxPriority, ignoreDirective, attrStartName,
  1291. attrEndName);
  1292. }
  1293. // use class as directive
  1294. className = node.className;
  1295. if (isString(className) && className !== '') {
  1296. while (match = CLASS_DIRECTIVE_REGEXP.exec(className)) {
  1297. nName = directiveNormalize(match[2]);
  1298. if (addDirective(directives, nName, 'C', maxPriority, ignoreDirective)) {
  1299. attrs[nName] = trim(match[3]);
  1300. }
  1301. className = className.substr(match.index + match[0].length);
  1302. }
  1303. }
  1304. break;
  1305. case NODE_TYPE_TEXT: /* Text Node */
  1306. addTextInterpolateDirective(directives, node.nodeValue);
  1307. break;
  1308. case NODE_TYPE_COMMENT: /* Comment */
  1309. try {
  1310. match = COMMENT_DIRECTIVE_REGEXP.exec(node.nodeValue);
  1311. if (match) {
  1312. nName = directiveNormalize(match[1]);
  1313. if (addDirective(directives, nName, 'M', maxPriority, ignoreDirective)) {
  1314. attrs[nName] = trim(match[2]);
  1315. }
  1316. }
  1317. } catch (e) {
  1318. // turns out that under some circumstances IE9 throws errors when one attempts to read
  1319. // comment's node value.
  1320. // Just ignore it and continue. (Can't seem to reproduce in test case.)
  1321. }
  1322. break;
  1323. }
  1324. directives.sort(byPriority);
  1325. return directives;
  1326. }
  1327. /**
  1328. * Given a node with an directive-start it collects all of the siblings until it finds
  1329. * directive-end.
  1330. * @param node
  1331. * @param attrStart
  1332. * @param attrEnd
  1333. * @returns {*}
  1334. */
  1335. function groupScan(node, attrStart, attrEnd) {
  1336. var nodes = [];
  1337. var depth = 0;
  1338. if (attrStart && node.hasAttribute && node.hasAttribute(attrStart)) {
  1339. do {
  1340. if (!node) {
  1341. throw $compileMinErr('uterdir',
  1342. "Unterminated attribute, found '{0}' but no matching '{1}' found.",
  1343. attrStart, attrEnd);
  1344. }
  1345. if (node.nodeType == NODE_TYPE_ELEMENT) {
  1346. if (node.hasAttribute(attrStart)) depth++;
  1347. if (node.hasAttribute(attrEnd)) depth--;
  1348. }
  1349. nodes.push(node);
  1350. node = node.nextSibling;
  1351. } while (depth > 0);
  1352. } else {
  1353. nodes.push(node);
  1354. }
  1355. return jqLite(nodes);
  1356. }
  1357. /**
  1358. * Wrapper for linking function which converts normal linking function into a grouped
  1359. * linking function.
  1360. * @param linkFn
  1361. * @param attrStart
  1362. * @param attrEnd
  1363. * @returns {Function}
  1364. */
  1365. function groupElementsLinkFnWrapper(linkFn, attrStart, attrEnd) {
  1366. return function(scope, element, attrs, controllers, transcludeFn) {
  1367. element = groupScan(element[0], attrStart, attrEnd);
  1368. return linkFn(scope, element, attrs, controllers, transcludeFn);
  1369. };
  1370. }
  1371. /**
  1372. * Once the directives have been collected, their compile functions are executed. This method
  1373. * is responsible for inlining directive templates as well as terminating the application
  1374. * of the directives if the terminal directive has been reached.
  1375. *
  1376. * @param {Array} directives Array of collected directives to execute their compile function.
  1377. * this needs to be pre-sorted by priority order.
  1378. * @param {Node} compileNode The raw DOM node to apply the compile functions to
  1379. * @param {Object} templateAttrs The shared attribute function
  1380. * @param {function(angular.Scope, cloneAttachFn=)} transcludeFn A linking function, where the
  1381. * scope argument is auto-generated to the new
  1382. * child of the transcluded parent scope.
  1383. * @param {JQLite} jqCollection If we are working on the root of the compile tree then this
  1384. * argument has the root jqLite array so that we can replace nodes
  1385. * on it.
  1386. * @param {Object=} originalReplaceDirective An optional directive that will be ignored when
  1387. * compiling the transclusion.
  1388. * @param {Array.<Function>} preLinkFns
  1389. * @param {Array.<Function>} postLinkFns
  1390. * @param {Object} previousCompileContext Context used for previous compilation of the current
  1391. * node
  1392. * @returns {Function} linkFn
  1393. */
  1394. function applyDirectivesToNode(directives, compileNode, templateAttrs, transcludeFn,
  1395. jqCollection, originalReplaceDirective, preLinkFns, postLinkFns,
  1396. previousCompileContext) {
  1397. previousCompileContext = previousCompileContext || {};
  1398. var terminalPriority = -Number.MAX_VALUE,
  1399. newScopeDirective,
  1400. controllerDirectives = previousCompileContext.controllerDirectives,
  1401. controllers,
  1402. newIsolateScopeDirective = previousCompileContext.newIsolateScopeDirective,
  1403. templateDirective = previousCompileContext.templateDirective,
  1404. nonTlbTranscludeDirective = previousCompileContext.nonTlbTranscludeDirective,
  1405. hasTranscludeDirective = false,
  1406. hasTemplate = false,
  1407. hasElementTranscludeDirective = previousCompileContext.hasElementTranscludeDirective,
  1408. $compileNode = templateAttrs.$$element = jqLite(compileNode),
  1409. directive,
  1410. directiveName,
  1411. $template,
  1412. replaceDirective = originalReplaceDirective,
  1413. childTranscludeFn = transcludeFn,
  1414. linkFn,
  1415. directiveValue;
  1416. // executes all directives on the current element
  1417. for (var i = 0, ii = directives.length; i < ii; i++) {
  1418. directive = directives[i];
  1419. var attrStart = directive.$$start;
  1420. var attrEnd = directive.$$end;
  1421. // collect multiblock sections
  1422. if (attrStart) {
  1423. $compileNode = groupScan(compileNode, attrStart, attrEnd);
  1424. }
  1425. $template = undefined;
  1426. if (terminalPriority > directive.priority) {
  1427. break; // prevent further processing of directives
  1428. }
  1429. if (directiveValue = directive.scope) {
  1430. // skip the check for directives with async templates, we'll check the derived sync
  1431. // directive when the template arrives
  1432. if (!directive.templateUrl) {
  1433. if (isObject(directiveValue)) {
  1434. // This directive is trying to add an isolated scope.
  1435. // Check that there is no scope of any kind already
  1436. assertNoDuplicate('new/isolated scope', newIsolateScopeDirective || newScopeDirective,
  1437. directive, $compileNode);
  1438. newIsolateScopeDirective = directive;
  1439. } else {
  1440. // This directive is trying to add a child scope.
  1441. // Check that there is no isolated scope already
  1442. assertNoDuplicate('new/isolated scope', newIsolateScopeDirective, directive,
  1443. $compileNode);
  1444. }
  1445. }
  1446. newScopeDirective = newScopeDirective || directive;
  1447. }
  1448. directiveName = directive.name;
  1449. if (!directive.templateUrl && directive.controller) {
  1450. directiveValue = directive.controller;
  1451. controllerDirectives = controllerDirectives || {};
  1452. assertNoDuplicate("'" + directiveName + "' controller",
  1453. controllerDirectives[directiveName], directive, $compileNode);
  1454. controllerDirectives[directiveName] = directive;
  1455. }
  1456. if (directiveValue = directive.transclude) {
  1457. hasTranscludeDirective = true;
  1458. // Special case ngIf and ngRepeat so that we don't complain about duplicate transclusion.
  1459. // This option should only be used by directives that know how to safely handle element transclusion,
  1460. // where the transcluded nodes are added or replaced after linking.
  1461. if (!directive.$$tlb) {
  1462. assertNoDuplicate('transclusion', nonTlbTranscludeDirective, directive, $compileNode);
  1463. nonTlbTranscludeDirective = directive;
  1464. }
  1465. if (directiveValue == 'element') {
  1466. hasElementTranscludeDirective = true;
  1467. terminalPriority = directive.priority;
  1468. $template = $compileNode;
  1469. $compileNode = templateAttrs.$$element =
  1470. jqLite(document.createComment(' ' + directiveName + ': ' +
  1471. templateAttrs[directiveName] + ' '));
  1472. compileNode = $compileNode[0];
  1473. replaceWith(jqCollection, sliceArgs($template), compileNode);
  1474. childTranscludeFn = compile($template, transcludeFn, terminalPriority,
  1475. replaceDirective && replaceDirective.name, {
  1476. // Don't pass in:
  1477. // - controllerDirectives - otherwise we'll create duplicates controllers
  1478. // - newIsolateScopeDirective or templateDirective - combining templates with
  1479. // element transclusion doesn't make sense.
  1480. //
  1481. // We need only nonTlbTranscludeDirective so that we prevent putting transclusion
  1482. // on the same element more than once.
  1483. nonTlbTranscludeDirective: nonTlbTranscludeDirective
  1484. });
  1485. } else {
  1486. $template = jqLite(jqLiteClone(compileNode)).contents();
  1487. $compileNode.empty(); // clear contents
  1488. childTranscludeFn = compile($template, transcludeFn);
  1489. }
  1490. }
  1491. if (directive.template) {
  1492. hasTemplate = true;
  1493. assertNoDuplicate('template', templateDirective, directive, $compileNode);
  1494. templateDirective = directive;
  1495. directiveValue = (isFunction(directive.template))
  1496. ? directive.template($compileNode, templateAttrs)
  1497. : directive.template;
  1498. directiveValue = denormalizeTemplate(directiveValue);
  1499. if (directive.replace) {
  1500. replaceDirective = directive;
  1501. if (jqLiteIsTextNode(directiveValue)) {
  1502. $template = [];
  1503. } else {
  1504. $template = removeComments(wrapTemplate(directive.templateNamespace, trim(directiveValue)));
  1505. }
  1506. compileNode = $template[0];
  1507. if ($template.length != 1 || compileNode.nodeType !== NODE_TYPE_ELEMENT) {
  1508. throw $compileMinErr('tplrt',
  1509. "Template for directive '{0}' must have exactly one root element. {1}",
  1510. directiveName, '');
  1511. }
  1512. replaceWith(jqCollection, $compileNode, compileNode);
  1513. var newTemplateAttrs = {$attr: {}};
  1514. // combine directives from the original node and from the template:
  1515. // - take the array of directives for this element
  1516. // - split it into two parts, those that already applied (processed) and those that weren't (unprocessed)
  1517. // - collect directives from the template and sort them by priority
  1518. // - combine directives as: processed + template + unprocessed
  1519. var templateDirectives = collectDirectives(compileNode, [], newTemplateAttrs);
  1520. var unprocessedDirectives = directives.splice(i + 1, directives.length - (i + 1));
  1521. if (newIsolateScopeDirective) {
  1522. markDirectivesAsIsolate(templateDirectives);
  1523. }
  1524. directives = directives.concat(templateDirectives).concat(unprocessedDirectives);
  1525. mergeTemplateAttributes(templateAttrs, newTemplateAttrs);
  1526. ii = directives.length;
  1527. } else {
  1528. $compileNode.html(directiveValue);
  1529. }
  1530. }
  1531. if (directive.templateUrl) {
  1532. hasTemplate = true;
  1533. assertNoDuplicate('template', templateDirective, directive, $compileNode);
  1534. templateDirective = directive;
  1535. if (directive.replace) {
  1536. replaceDirective = directive;
  1537. }
  1538. nodeLinkFn = compileTemplateUrl(directives.splice(i, directives.length - i), $compileNode,
  1539. templateAttrs, jqCollection, hasTranscludeDirective && childTranscludeFn, preLinkFns, postLinkFns, {
  1540. controllerDirectives: controllerDirectives,
  1541. newIsolateScopeDirective: newIsolateScopeDirective,
  1542. templateDirective: templateDirective,
  1543. nonTlbTranscludeDirective: nonTlbTranscludeDirective
  1544. });
  1545. ii = directives.length;
  1546. } else if (directive.compile) {
  1547. try {
  1548. linkFn = directive.compile($compileNode, templateAttrs, childTranscludeFn);
  1549. if (isFunction(linkFn)) {
  1550. addLinkFns(null, linkFn, attrStart, attrEnd);
  1551. } else if (linkFn) {
  1552. addLinkFns(linkFn.pre, linkFn.post, attrStart, attrEnd);
  1553. }
  1554. } catch (e) {
  1555. $exceptionHandler(e, startingTag($compileNode));
  1556. }
  1557. }
  1558. if (directive.terminal) {
  1559. nodeLinkFn.terminal = true;
  1560. terminalPriority = Math.max(terminalPriority, directive.priority);
  1561. }
  1562. }
  1563. nodeLinkFn.scope = newScopeDirective && newScopeDirective.scope === true;
  1564. nodeLinkFn.transcludeOnThisElement = hasTranscludeDirective;
  1565. nodeLinkFn.elementTranscludeOnThisElement = hasElementTranscludeDirective;
  1566. nodeLinkFn.templateOnThisElement = hasTemplate;
  1567. nodeLinkFn.transclude = childTranscludeFn;
  1568. previousCompileContext.hasElementTranscludeDirective = hasElementTranscludeDirective;
  1569. // might be normal or delayed nodeLinkFn depending on if templateUrl is present
  1570. return nodeLinkFn;
  1571. ////////////////////
  1572. function addLinkFns(pre, post, attrStart, attrEnd) {
  1573. if (pre) {
  1574. if (attrStart) pre = groupElementsLinkFnWrapper(pre, attrStart, attrEnd);
  1575. pre.require = directive.require;
  1576. pre.directiveName = directiveName;
  1577. if (newIsolateScopeDirective === directive || directive.$$isolateScope) {
  1578. pre = cloneAndAnnotateFn(pre, {isolateScope: true});
  1579. }
  1580. preLinkFns.push(pre);
  1581. }
  1582. if (post) {
  1583. if (attrStart) post = groupElementsLinkFnWrapper(post, attrStart, attrEnd);
  1584. post.require = directive.require;
  1585. post.directiveName = directiveName;
  1586. if (newIsolateScopeDirective === directive || directive.$$isolateScope) {
  1587. post = cloneAndAnnotateFn(post, {isolateScope: true});
  1588. }
  1589. postLinkFns.push(post);
  1590. }
  1591. }
  1592. function getControllers(directiveName, require, $element, elementControllers) {
  1593. var value, retrievalMethod = 'data', optional = false;
  1594. var $searchElement = $element;
  1595. var match;
  1596. if (isString(require)) {
  1597. match = require.match(REQUIRE_PREFIX_REGEXP);
  1598. require = require.substring(match[0].length);
  1599. if (match[3]) {
  1600. if (match[1]) match[3] = null;
  1601. else match[1] = match[3];
  1602. }
  1603. if (match[1] === '^') {
  1604. retrievalMethod = 'inheritedData';
  1605. } else if (match[1] === '^^') {
  1606. retrievalMethod = 'inheritedData';
  1607. $searchElement = $element.parent();
  1608. }
  1609. if (match[2] === '?') {
  1610. optional = true;
  1611. }
  1612. value = null;
  1613. if (elementControllers && retrievalMethod === 'data') {
  1614. if (value = elementControllers[require]) {
  1615. value = value.instance;
  1616. }
  1617. }
  1618. value = value || $searchElement[retrievalMethod]('$' + require + 'Controller');
  1619. if (!value && !optional) {
  1620. throw $compileMinErr('ctreq',
  1621. "Controller '{0}', required by directive '{1}', can't be found!",
  1622. require, directiveName);
  1623. }
  1624. return value || null;
  1625. } else if (isArray(require)) {
  1626. value = [];
  1627. forEach(require, function(require) {
  1628. value.push(getControllers(directiveName, require, $element, elementControllers));
  1629. });
  1630. }
  1631. return value;
  1632. }
  1633. function nodeLinkFn(childLinkFn, scope, linkNode, $rootElement, boundTranscludeFn) {
  1634. var i, ii, linkFn, controller, isolateScope, elementControllers, transcludeFn, $element,
  1635. attrs;
  1636. if (compileNode === linkNode) {
  1637. attrs = templateAttrs;
  1638. $element = templateAttrs.$$element;
  1639. } else {
  1640. $element = jqLite(linkNode);
  1641. attrs = new Attributes($element, templateAttrs);
  1642. }
  1643. if (newIsolateScopeDirective) {
  1644. isolateScope = scope.$new(true);
  1645. }
  1646. transcludeFn = boundTranscludeFn && controllersBoundTransclude;
  1647. if (controllerDirectives) {
  1648. // TODO: merge `controllers` and `elementControllers` into single object.
  1649. controllers = {};
  1650. elementControllers = {};
  1651. forEach(controllerDirectives, function(directive) {
  1652. var locals = {
  1653. $scope: directive === newIsolateScopeDirective || directive.$$isolateScope ? isolateScope : scope,
  1654. $element: $element,
  1655. $attrs: attrs,
  1656. $transclude: transcludeFn
  1657. }, controllerInstance;
  1658. controller = directive.controller;
  1659. if (controller == '@') {
  1660. controller = attrs[directive.name];
  1661. }
  1662. controllerInstance = $controller(controller, locals, true, directive.controllerAs);
  1663. // For directives with element transclusion the element is a comment,
  1664. // but jQuery .data doesn't support attaching data to comment nodes as it's hard to
  1665. // clean up (http://bugs.jquery.com/ticket/8335).
  1666. // Instead, we save the controllers for the element in a local hash and attach to .data
  1667. // later, once we have the actual element.
  1668. elementControllers[directive.name] = controllerInstance;
  1669. if (!hasElementTranscludeDirective) {
  1670. $element.data('$' + directive.name + 'Controller', controllerInstance.instance);
  1671. }
  1672. controllers[directive.name] = controllerInstance;
  1673. });
  1674. }
  1675. if (newIsolateScopeDirective) {
  1676. compile.$$addScopeInfo($element, isolateScope, true, !(templateDirective && (templateDirective === newIsolateScopeDirective ||
  1677. templateDirective === newIsolateScopeDirective.$$originalDirective)));
  1678. compile.$$addScopeClass($element, true);
  1679. var isolateScopeController = controllers && controllers[newIsolateScopeDirective.name];
  1680. var isolateBindingContext = isolateScope;
  1681. if (isolateScopeController && isolateScopeController.identifier &&
  1682. newIsolateScopeDirective.bindToController === true) {
  1683. isolateBindingContext = isolateScopeController.instance;
  1684. }
  1685. forEach(isolateScope.$$isolateBindings = newIsolateScopeDirective.$$isolateBindings, function(definition, scopeName) {
  1686. var attrName = definition.attrName,
  1687. optional = definition.optional,
  1688. mode = definition.mode, // @, =, or &
  1689. lastValue,
  1690. parentGet, parentSet, compare;
  1691. switch (mode) {
  1692. case '@':
  1693. attrs.$observe(attrName, function(value) {
  1694. isolateBindingContext[scopeName] = value;
  1695. });
  1696. attrs.$$observers[attrName].$$scope = scope;
  1697. if (attrs[attrName]) {
  1698. // If the attribute has been provided then we trigger an interpolation to ensure
  1699. // the value is there for use in the link fn
  1700. isolateBindingContext[scopeName] = $interpolate(attrs[attrName])(scope);
  1701. }
  1702. break;
  1703. case '=':
  1704. if (optional && !attrs[attrName]) {
  1705. return;
  1706. }
  1707. parentGet = $parse(attrs[attrName]);
  1708. if (parentGet.literal) {
  1709. compare = equals;
  1710. } else {
  1711. compare = function(a, b) { return a === b || (a !== a && b !== b); };
  1712. }
  1713. parentSet = parentGet.assign || function() {
  1714. // reset the change, or we will throw this exception on every $digest
  1715. lastValue = isolateBindingContext[scopeName] = parentGet(scope);
  1716. throw $compileMinErr('nonassign',
  1717. "Expression '{0}' used with directive '{1}' is non-assignable!",
  1718. attrs[attrName], newIsolateScopeDirective.name);
  1719. };
  1720. lastValue = isolateBindingContext[scopeName] = parentGet(scope);
  1721. var parentValueWatch = function parentValueWatch(parentValue) {
  1722. if (!compare(parentValue, isolateBindingContext[scopeName])) {
  1723. // we are out of sync and need to copy
  1724. if (!compare(parentValue, lastValue)) {
  1725. // parent changed and it has precedence
  1726. isolateBindingContext[scopeName] = parentValue;
  1727. } else {
  1728. // if the parent can be assigned then do so
  1729. parentSet(scope, parentValue = isolateBindingContext[scopeName]);
  1730. }
  1731. }
  1732. return lastValue = parentValue;
  1733. };
  1734. parentValueWatch.$stateful = true;
  1735. var unwatch;
  1736. if (definition.collection) {
  1737. unwatch = scope.$watchCollection(attrs[attrName], parentValueWatch);
  1738. } else {
  1739. unwatch = scope.$watch($parse(attrs[attrName], parentValueWatch), null, parentGet.literal);
  1740. }
  1741. isolateScope.$on('$destroy', unwatch);
  1742. break;
  1743. case '&':
  1744. parentGet = $parse(attrs[attrName]);
  1745. isolateBindingContext[scopeName] = function(locals) {
  1746. return parentGet(scope, locals);
  1747. };
  1748. break;
  1749. }
  1750. });
  1751. }
  1752. if (controllers) {
  1753. forEach(controllers, function(controller) {
  1754. controller();
  1755. });
  1756. controllers = null;
  1757. }
  1758. // PRELINKING
  1759. for (i = 0, ii = preLinkFns.length; i < ii; i++) {
  1760. linkFn = preLinkFns[i];
  1761. invokeLinkFn(linkFn,
  1762. linkFn.isolateScope ? isolateScope : scope,
  1763. $element,
  1764. attrs,
  1765. linkFn.require && getControllers(linkFn.directiveName, linkFn.require, $element, elementControllers),
  1766. transcludeFn
  1767. );
  1768. }
  1769. // RECURSION
  1770. // We only pass the isolate scope, if the isolate directive has a template,
  1771. // otherwise the child elements do not belong to the isolate directive.
  1772. var scopeToChild = scope;
  1773. if (newIsolateScopeDirective && (newIsolateScopeDirective.template || newIsolateScopeDirective.templateUrl === null)) {
  1774. scopeToChild = isolateScope;
  1775. }
  1776. childLinkFn && childLinkFn(scopeToChild, linkNode.childNodes, undefined, boundTranscludeFn);
  1777. // POSTLINKING
  1778. for (i = postLinkFns.length - 1; i >= 0; i--) {
  1779. linkFn = postLinkFns[i];
  1780. invokeLinkFn(linkFn,
  1781. linkFn.isolateScope ? isolateScope : scope,
  1782. $element,
  1783. attrs,
  1784. linkFn.require && getControllers(linkFn.directiveName, linkFn.require, $element, elementControllers),
  1785. transcludeFn
  1786. );
  1787. }
  1788. // This is the function that is injected as `$transclude`.
  1789. // Note: all arguments are optional!
  1790. function controllersBoundTransclude(scope, cloneAttachFn, futureParentElement) {
  1791. var transcludeControllers;
  1792. // No scope passed in:
  1793. if (!isScope(scope)) {
  1794. futureParentElement = cloneAttachFn;
  1795. cloneAttachFn = scope;
  1796. scope = undefined;
  1797. }
  1798. if (hasElementTranscludeDirective) {
  1799. transcludeControllers = elementControllers;
  1800. }
  1801. if (!futureParentElement) {
  1802. futureParentElement = hasElementTranscludeDirective ? $element.parent() : $element;
  1803. }
  1804. return boundTranscludeFn(scope, cloneAttachFn, transcludeControllers, futureParentElement, scopeToChild);
  1805. }
  1806. }
  1807. }
  1808. function markDirectivesAsIsolate(directives) {
  1809. // mark all directives as needing isolate scope.
  1810. for (var j = 0, jj = directives.length; j < jj; j++) {
  1811. directives[j] = inherit(directives[j], {$$isolateScope: true});
  1812. }
  1813. }
  1814. /**
  1815. * looks up the directive and decorates it with exception handling and proper parameters. We
  1816. * call this the boundDirective.
  1817. *
  1818. * @param {string} name name of the directive to look up.
  1819. * @param {string} location The directive must be found in specific format.
  1820. * String containing any of theses characters:
  1821. *
  1822. * * `E`: element name
  1823. * * `A': attribute
  1824. * * `C`: class
  1825. * * `M`: comment
  1826. * @returns {boolean} true if directive was added.
  1827. */
  1828. function addDirective(tDirectives, name, location, maxPriority, ignoreDirective, startAttrName,
  1829. endAttrName) {
  1830. if (name === ignoreDirective) return null;
  1831. var match = null;
  1832. if (hasDirectives.hasOwnProperty(name)) {
  1833. for (var directive, directives = $injector.get(name + Suffix),
  1834. i = 0, ii = directives.length; i<ii; i++) {
  1835. try {
  1836. directive = directives[i];
  1837. if ((maxPriority === undefined || maxPriority > directive.priority) &&
  1838. directive.restrict.indexOf(location) != -1) {
  1839. if (startAttrName) {
  1840. directive = inherit(directive, {$$start: startAttrName, $$end: endAttrName});
  1841. }
  1842. tDirectives.push(directive);
  1843. match = directive;
  1844. }
  1845. } catch (e) { $exceptionHandler(e); }
  1846. }
  1847. }
  1848. return match;
  1849. }
  1850. /**
  1851. * looks up the directive and returns true if it is a multi-element directive,
  1852. * and therefore requires DOM nodes between -start and -end markers to be grouped
  1853. * together.
  1854. *
  1855. * @param {string} name name of the directive to look up.
  1856. * @returns true if directive was registered as multi-element.
  1857. */
  1858. function directiveIsMultiElement(name) {
  1859. if (hasDirectives.hasOwnProperty(name)) {
  1860. for (var directive, directives = $injector.get(name + Suffix),
  1861. i = 0, ii = directives.length; i<ii; i++) {
  1862. directive = directives[i];
  1863. if (directive.multiElement) {
  1864. return true;
  1865. }
  1866. }
  1867. }
  1868. return false;
  1869. }
  1870. /**
  1871. * When the element is replaced with HTML template then the new attributes
  1872. * on the template need to be merged with the existing attributes in the DOM.
  1873. * The desired effect is to have both of the attributes present.
  1874. *
  1875. * @param {object} dst destination attributes (original DOM)
  1876. * @param {object} src source attributes (from the directive template)
  1877. */
  1878. function mergeTemplateAttributes(dst, src) {
  1879. var srcAttr = src.$attr,
  1880. dstAttr = dst.$attr,
  1881. $element = dst.$$element;
  1882. // reapply the old attributes to the new element
  1883. forEach(dst, function(value, key) {
  1884. if (key.charAt(0) != '$') {
  1885. if (src[key] && src[key] !== value) {
  1886. value += (key === 'style' ? ';' : ' ') + src[key];
  1887. }
  1888. dst.$set(key, value, true, srcAttr[key]);
  1889. }
  1890. });
  1891. // copy the new attributes on the old attrs object
  1892. forEach(src, function(value, key) {
  1893. if (key == 'class') {
  1894. safeAddClass($element, value);
  1895. dst['class'] = (dst['class'] ? dst['class'] + ' ' : '') + value;
  1896. } else if (key == 'style') {
  1897. $element.attr('style', $element.attr('style') + ';' + value);
  1898. dst['style'] = (dst['style'] ? dst['style'] + ';' : '') + value;
  1899. // `dst` will never contain hasOwnProperty as DOM parser won't let it.
  1900. // You will get an "InvalidCharacterError: DOM Exception 5" error if you
  1901. // have an attribute like "has-own-property" or "data-has-own-property", etc.
  1902. } else if (key.charAt(0) != '$' && !dst.hasOwnProperty(key)) {
  1903. dst[key] = value;
  1904. dstAttr[key] = srcAttr[key];
  1905. }
  1906. });
  1907. }
  1908. function compileTemplateUrl(directives, $compileNode, tAttrs,
  1909. $rootElement, childTranscludeFn, preLinkFns, postLinkFns, previousCompileContext) {
  1910. var linkQueue = [],
  1911. afterTemplateNodeLinkFn,
  1912. afterTemplateChildLinkFn,
  1913. beforeTemplateCompileNode = $compileNode[0],
  1914. origAsyncDirective = directives.shift(),
  1915. // The fact that we have to copy and patch the directive seems wrong!
  1916. derivedSyncDirective = extend({}, origAsyncDirective, {
  1917. templateUrl: null, transclude: null, replace: null, $$originalDirective: origAsyncDirective
  1918. }),
  1919. templateUrl = (isFunction(origAsyncDirective.templateUrl))
  1920. ? origAsyncDirective.templateUrl($compileNode, tAttrs)
  1921. : origAsyncDirective.templateUrl,
  1922. templateNamespace = origAsyncDirective.templateNamespace;
  1923. $compileNode.empty();
  1924. $templateRequest($sce.getTrustedResourceUrl(templateUrl))
  1925. .then(function(content) {
  1926. var compileNode, tempTemplateAttrs, $template, childBoundTranscludeFn;
  1927. content = denormalizeTemplate(content);
  1928. if (origAsyncDirective.replace) {
  1929. if (jqLiteIsTextNode(content)) {
  1930. $template = [];
  1931. } else {
  1932. $template = removeComments(wrapTemplate(templateNamespace, trim(content)));
  1933. }
  1934. compileNode = $template[0];
  1935. if ($template.length != 1 || compileNode.nodeType !== NODE_TYPE_ELEMENT) {
  1936. throw $compileMinErr('tplrt',
  1937. "Template for directive '{0}' must have exactly one root element. {1}",
  1938. origAsyncDirective.name, templateUrl);
  1939. }
  1940. tempTemplateAttrs = {$attr: {}};
  1941. replaceWith($rootElement, $compileNode, compileNode);
  1942. var templateDirectives = collectDirectives(compileNode, [], tempTemplateAttrs);
  1943. if (isObject(origAsyncDirective.scope)) {
  1944. markDirectivesAsIsolate(templateDirectives);
  1945. }
  1946. directives = templateDirectives.concat(directives);
  1947. mergeTemplateAttributes(tAttrs, tempTemplateAttrs);
  1948. } else {
  1949. compileNode = beforeTemplateCompileNode;
  1950. $compileNode.html(content);
  1951. }
  1952. directives.unshift(derivedSyncDirective);
  1953. afterTemplateNodeLinkFn = applyDirectivesToNode(directives, compileNode, tAttrs,
  1954. childTranscludeFn, $compileNode, origAsyncDirective, preLinkFns, postLinkFns,
  1955. previousCompileContext);
  1956. forEach($rootElement, function(node, i) {
  1957. if (node == compileNode) {
  1958. $rootElement[i] = $compileNode[0];
  1959. }
  1960. });
  1961. afterTemplateChildLinkFn = compileNodes($compileNode[0].childNodes, childTranscludeFn);
  1962. while (linkQueue.length) {
  1963. var scope = linkQueue.shift(),
  1964. beforeTemplateLinkNode = linkQueue.shift(),
  1965. linkRootElement = linkQueue.shift(),
  1966. boundTranscludeFn = linkQueue.shift(),
  1967. linkNode = $compileNode[0];
  1968. if (scope.$$destroyed) continue;
  1969. if (beforeTemplateLinkNode !== beforeTemplateCompileNode) {
  1970. var oldClasses = beforeTemplateLinkNode.className;
  1971. if (!(previousCompileContext.hasElementTranscludeDirective &&
  1972. origAsyncDirective.replace)) {
  1973. // it was cloned therefore we have to clone as well.
  1974. linkNode = jqLiteClone(compileNode);
  1975. }
  1976. replaceWith(linkRootElement, jqLite(beforeTemplateLinkNode), linkNode);
  1977. // Copy in CSS classes from original node
  1978. safeAddClass(jqLite(linkNode), oldClasses);
  1979. }
  1980. if (afterTemplateNodeLinkFn.transcludeOnThisElement) {
  1981. childBoundTranscludeFn = createBoundTranscludeFn(scope, afterTemplateNodeLinkFn.transclude, boundTranscludeFn);
  1982. } else {
  1983. childBoundTranscludeFn = boundTranscludeFn;
  1984. }
  1985. afterTemplateNodeLinkFn(afterTemplateChildLinkFn, scope, linkNode, $rootElement,
  1986. childBoundTranscludeFn);
  1987. }
  1988. linkQueue = null;
  1989. });
  1990. return function delayedNodeLinkFn(ignoreChildLinkFn, scope, node, rootElement, boundTranscludeFn) {
  1991. var childBoundTranscludeFn = boundTranscludeFn;
  1992. if (scope.$$destroyed) return;
  1993. if (linkQueue) {
  1994. linkQueue.push(scope);
  1995. linkQueue.push(node);
  1996. linkQueue.push(rootElement);
  1997. linkQueue.push(childBoundTranscludeFn);
  1998. } else {
  1999. if (afterTemplateNodeLinkFn.transcludeOnThisElement) {
  2000. childBoundTranscludeFn = createBoundTranscludeFn(scope, afterTemplateNodeLinkFn.transclude, boundTranscludeFn);
  2001. }
  2002. afterTemplateNodeLinkFn(afterTemplateChildLinkFn, scope, node, rootElement, childBoundTranscludeFn);
  2003. }
  2004. };
  2005. }
  2006. /**
  2007. * Sorting function for bound directives.
  2008. */
  2009. function byPriority(a, b) {
  2010. var diff = b.priority - a.priority;
  2011. if (diff !== 0) return diff;
  2012. if (a.name !== b.name) return (a.name < b.name) ? -1 : 1;
  2013. return a.index - b.index;
  2014. }
  2015. function assertNoDuplicate(what, previousDirective, directive, element) {
  2016. if (previousDirective) {
  2017. throw $compileMinErr('multidir', 'Multiple directives [{0}, {1}] asking for {2} on: {3}',
  2018. previousDirective.name, directive.name, what, startingTag(element));
  2019. }
  2020. }
  2021. function addTextInterpolateDirective(directives, text) {
  2022. var interpolateFn = $interpolate(text, true);
  2023. if (interpolateFn) {
  2024. directives.push({
  2025. priority: 0,
  2026. compile: function textInterpolateCompileFn(templateNode) {
  2027. var templateNodeParent = templateNode.parent(),
  2028. hasCompileParent = !!templateNodeParent.length;
  2029. // When transcluding a template that has bindings in the root
  2030. // we don't have a parent and thus need to add the class during linking fn.
  2031. if (hasCompileParent) compile.$$addBindingClass(templateNodeParent);
  2032. return function textInterpolateLinkFn(scope, node) {
  2033. var parent = node.parent();
  2034. if (!hasCompileParent) compile.$$addBindingClass(parent);
  2035. compile.$$addBindingInfo(parent, interpolateFn.expressions);
  2036. scope.$watch(interpolateFn, function interpolateFnWatchAction(value) {
  2037. node[0].nodeValue = value;
  2038. });
  2039. };
  2040. }
  2041. });
  2042. }
  2043. }
  2044. function wrapTemplate(type, template) {
  2045. type = lowercase(type || 'html');
  2046. switch (type) {
  2047. case 'svg':
  2048. case 'math':
  2049. var wrapper = document.createElement('div');
  2050. wrapper.innerHTML = '<'+type+'>'+template+'</'+type+'>';
  2051. return wrapper.childNodes[0].childNodes;
  2052. default:
  2053. return template;
  2054. }
  2055. }
  2056. function getTrustedContext(node, attrNormalizedName) {
  2057. if (attrNormalizedName == "srcdoc") {
  2058. return $sce.HTML;
  2059. }
  2060. var tag = nodeName_(node);
  2061. // maction[xlink:href] can source SVG. It's not limited to <maction>.
  2062. if (attrNormalizedName == "xlinkHref" ||
  2063. (tag == "form" && attrNormalizedName == "action") ||
  2064. (tag != "img" && (attrNormalizedName == "src" ||
  2065. attrNormalizedName == "ngSrc"))) {
  2066. return $sce.RESOURCE_URL;
  2067. }
  2068. }
  2069. function addAttrInterpolateDirective(node, directives, value, name, allOrNothing) {
  2070. var interpolateFn = $interpolate(value, true);
  2071. // no interpolation found -> ignore
  2072. if (!interpolateFn) return;
  2073. if (name === "multiple" && nodeName_(node) === "select") {
  2074. throw $compileMinErr("selmulti",
  2075. "Binding to the 'multiple' attribute is not supported. Element: {0}",
  2076. startingTag(node));
  2077. }
  2078. directives.push({
  2079. priority: 100,
  2080. compile: function() {
  2081. return {
  2082. pre: function attrInterpolatePreLinkFn(scope, element, attr) {
  2083. var $$observers = (attr.$$observers || (attr.$$observers = {}));
  2084. if (EVENT_HANDLER_ATTR_REGEXP.test(name)) {
  2085. throw $compileMinErr('nodomevents',
  2086. "Interpolations for HTML DOM event attributes are disallowed. Please use the " +
  2087. "ng- versions (such as ng-click instead of onclick) instead.");
  2088. }
  2089. // If the attribute was removed, then we are done
  2090. if (!attr[name]) {
  2091. return;
  2092. }
  2093. // we need to interpolate again, in case the attribute value has been updated
  2094. // (e.g. by another directive's compile function)
  2095. interpolateFn = $interpolate(attr[name], true, getTrustedContext(node, name),
  2096. ALL_OR_NOTHING_ATTRS[name] || allOrNothing);
  2097. // if attribute was updated so that there is no interpolation going on we don't want to
  2098. // register any observers
  2099. if (!interpolateFn) return;
  2100. // initialize attr object so that it's ready in case we need the value for isolate
  2101. // scope initialization, otherwise the value would not be available from isolate
  2102. // directive's linking fn during linking phase
  2103. attr[name] = interpolateFn(scope);
  2104. ($$observers[name] || ($$observers[name] = [])).$$inter = true;
  2105. (attr.$$observers && attr.$$observers[name].$$scope || scope).
  2106. $watch(interpolateFn, function interpolateFnWatchAction(newValue, oldValue) {
  2107. //special case for class attribute addition + removal
  2108. //so that class changes can tap into the animation
  2109. //hooks provided by the $animate service. Be sure to
  2110. //skip animations when the first digest occurs (when
  2111. //both the new and the old values are the same) since
  2112. //the CSS classes are the non-interpolated values
  2113. if (name === 'class' && newValue != oldValue) {
  2114. attr.$updateClass(newValue, oldValue);
  2115. } else {
  2116. attr.$set(name, newValue);
  2117. }
  2118. });
  2119. }
  2120. };
  2121. }
  2122. });
  2123. }
  2124. /**
  2125. * This is a special jqLite.replaceWith, which can replace items which
  2126. * have no parents, provided that the containing jqLite collection is provided.
  2127. *
  2128. * @param {JqLite=} $rootElement The root of the compile tree. Used so that we can replace nodes
  2129. * in the root of the tree.
  2130. * @param {JqLite} elementsToRemove The jqLite element which we are going to replace. We keep
  2131. * the shell, but replace its DOM node reference.
  2132. * @param {Node} newNode The new DOM node.
  2133. */
  2134. function replaceWith($rootElement, elementsToRemove, newNode) {
  2135. var firstElementToRemove = elementsToRemove[0],
  2136. removeCount = elementsToRemove.length,
  2137. parent = firstElementToRemove.parentNode,
  2138. i, ii;
  2139. if ($rootElement) {
  2140. for (i = 0, ii = $rootElement.length; i < ii; i++) {
  2141. if ($rootElement[i] == firstElementToRemove) {
  2142. $rootElement[i++] = newNode;
  2143. for (var j = i, j2 = j + removeCount - 1,
  2144. jj = $rootElement.length;
  2145. j < jj; j++, j2++) {
  2146. if (j2 < jj) {
  2147. $rootElement[j] = $rootElement[j2];
  2148. } else {
  2149. delete $rootElement[j];
  2150. }
  2151. }
  2152. $rootElement.length -= removeCount - 1;
  2153. // If the replaced element is also the jQuery .context then replace it
  2154. // .context is a deprecated jQuery api, so we should set it only when jQuery set it
  2155. // http://api.jquery.com/context/
  2156. if ($rootElement.context === firstElementToRemove) {
  2157. $rootElement.context = newNode;
  2158. }
  2159. break;
  2160. }
  2161. }
  2162. }
  2163. if (parent) {
  2164. parent.replaceChild(newNode, firstElementToRemove);
  2165. }
  2166. // TODO(perf): what's this document fragment for? is it needed? can we at least reuse it?
  2167. var fragment = document.createDocumentFragment();
  2168. fragment.appendChild(firstElementToRemove);
  2169. // Copy over user data (that includes Angular's $scope etc.). Don't copy private
  2170. // data here because there's no public interface in jQuery to do that and copying over
  2171. // event listeners (which is the main use of private data) wouldn't work anyway.
  2172. jqLite(newNode).data(jqLite(firstElementToRemove).data());
  2173. // Remove data of the replaced element. We cannot just call .remove()
  2174. // on the element it since that would deallocate scope that is needed
  2175. // for the new node. Instead, remove the data "manually".
  2176. if (!jQuery) {
  2177. delete jqLite.cache[firstElementToRemove[jqLite.expando]];
  2178. } else {
  2179. // jQuery 2.x doesn't expose the data storage. Use jQuery.cleanData to clean up after
  2180. // the replaced element. The cleanData version monkey-patched by Angular would cause
  2181. // the scope to be trashed and we do need the very same scope to work with the new
  2182. // element. However, we cannot just cache the non-patched version and use it here as
  2183. // that would break if another library patches the method after Angular does (one
  2184. // example is jQuery UI). Instead, set a flag indicating scope destroying should be
  2185. // skipped this one time.
  2186. skipDestroyOnNextJQueryCleanData = true;
  2187. jQuery.cleanData([firstElementToRemove]);
  2188. }
  2189. for (var k = 1, kk = elementsToRemove.length; k < kk; k++) {
  2190. var element = elementsToRemove[k];
  2191. jqLite(element).remove(); // must do this way to clean up expando
  2192. fragment.appendChild(element);
  2193. delete elementsToRemove[k];
  2194. }
  2195. elementsToRemove[0] = newNode;
  2196. elementsToRemove.length = 1;
  2197. }
  2198. function cloneAndAnnotateFn(fn, annotation) {
  2199. return extend(function() { return fn.apply(null, arguments); }, fn, annotation);
  2200. }
  2201. function invokeLinkFn(linkFn, scope, $element, attrs, controllers, transcludeFn) {
  2202. try {
  2203. linkFn(scope, $element, attrs, controllers, transcludeFn);
  2204. } catch (e) {
  2205. $exceptionHandler(e, startingTag($element));
  2206. }
  2207. }
  2208. }];
  2209. }
  2210. var PREFIX_REGEXP = /^((?:x|data)[\:\-_])/i;
  2211. /**
  2212. * Converts all accepted directives format into proper directive name.
  2213. * All of these will become 'myDirective':
  2214. * my:Directive
  2215. * my-directive
  2216. * x-my-directive
  2217. * data-my:directive
  2218. *
  2219. * Also there is special case for Moz prefix starting with upper case letter.
  2220. * @param name Name to normalize
  2221. */
  2222. function directiveNormalize(name) {
  2223. return camelCase(name.replace(PREFIX_REGEXP, ''));
  2224. }
  2225. /**
  2226. * @ngdoc type
  2227. * @name $compile.directive.Attributes
  2228. *
  2229. * @description
  2230. * A shared object between directive compile / linking functions which contains normalized DOM
  2231. * element attributes. The values reflect current binding state `{{ }}`. The normalization is
  2232. * needed since all of these are treated as equivalent in Angular:
  2233. *
  2234. * ```
  2235. * <span ng:bind="a" ng-bind="a" data-ng-bind="a" x-ng-bind="a">
  2236. * ```
  2237. */
  2238. /**
  2239. * @ngdoc property
  2240. * @name $compile.directive.Attributes#$attr
  2241. *
  2242. * @description
  2243. * A map of DOM element attribute names to the normalized name. This is
  2244. * needed to do reverse lookup from normalized name back to actual name.
  2245. */
  2246. /**
  2247. * @ngdoc method
  2248. * @name $compile.directive.Attributes#$set
  2249. * @kind function
  2250. *
  2251. * @description
  2252. * Set DOM element attribute value.
  2253. *
  2254. *
  2255. * @param {string} name Normalized element attribute name of the property to modify. The name is
  2256. * reverse-translated using the {@link ng.$compile.directive.Attributes#$attr $attr}
  2257. * property to the original name.
  2258. * @param {string} value Value to set the attribute to. The value can be an interpolated string.
  2259. */
  2260. /**
  2261. * Closure compiler type information
  2262. */
  2263. function nodesetLinkingFn(
  2264. /* angular.Scope */ scope,
  2265. /* NodeList */ nodeList,
  2266. /* Element */ rootElement,
  2267. /* function(Function) */ boundTranscludeFn
  2268. ) {}
  2269. function directiveLinkingFn(
  2270. /* nodesetLinkingFn */ nodesetLinkingFn,
  2271. /* angular.Scope */ scope,
  2272. /* Node */ node,
  2273. /* Element */ rootElement,
  2274. /* function(Function) */ boundTranscludeFn
  2275. ) {}
  2276. function tokenDifference(str1, str2) {
  2277. var values = '',
  2278. tokens1 = str1.split(/\s+/),
  2279. tokens2 = str2.split(/\s+/);
  2280. outer:
  2281. for (var i = 0; i < tokens1.length; i++) {
  2282. var token = tokens1[i];
  2283. for (var j = 0; j < tokens2.length; j++) {
  2284. if (token == tokens2[j]) continue outer;
  2285. }
  2286. values += (values.length > 0 ? ' ' : '') + token;
  2287. }
  2288. return values;
  2289. }
  2290. function removeComments(jqNodes) {
  2291. jqNodes = jqLite(jqNodes);
  2292. var i = jqNodes.length;
  2293. if (i <= 1) {
  2294. return jqNodes;
  2295. }
  2296. while (i--) {
  2297. var node = jqNodes[i];
  2298. if (node.nodeType === NODE_TYPE_COMMENT) {
  2299. splice.call(jqNodes, i, 1);
  2300. }
  2301. }
  2302. return jqNodes;
  2303. }