PageRenderTime 71ms CodeModel.GetById 24ms RepoModel.GetById 0ms app.codeStats 1ms

/src/ng/compile.js

https://github.com/IngageStroliaC/angular.js
JavaScript | 2000 lines | 966 code | 185 blank | 849 comment | 261 complexity | 304fcfce82cca232fee11f723b8de5dd MD5 | raw file
Possible License(s): JSON
  1. 'use strict';
  2. /* ! VARIABLE/FUNCTION NAMING CONVENTIONS THAT APPLY TO THIS FILE!
  3. *
  4. * DOM-related variables:
  5. *
  6. * - "node" - DOM Node
  7. * - "element" - DOM Element or Node
  8. * - "$node" or "$element" - jqLite-wrapped node or element
  9. *
  10. *
  11. * Compiler related stuff:
  12. *
  13. * - "linkFn" - linking fn of a single directive
  14. * - "nodeLinkFn" - function that aggregates all linking fns for a particular node
  15. * - "childLinkFn" - function that aggregates all linking fns for child nodes of a particular node
  16. * - "compositeLinkFn" - function that aggregates all linking fns for a compilation root (nodeList)
  17. */
  18. /**
  19. * @ngdoc function
  20. * @name ng.$compile
  21. * @function
  22. *
  23. * @description
  24. * Compiles a piece of HTML string or DOM into a template and produces a template function, which
  25. * can then be used to link {@link ng.$rootScope.Scope `scope`} and the template together.
  26. *
  27. * The compilation is a process of walking the DOM tree and matching DOM elements to
  28. * {@link ng.$compileProvider#methods_directive directives}.
  29. *
  30. * <div class="alert alert-warning">
  31. * **Note:** This document is an in-depth reference of all directive options.
  32. * For a gentle introduction to directives with examples of common use cases,
  33. * see the {@link guide/directive directive guide}.
  34. * </div>
  35. *
  36. * ## Comprehensive Directive API
  37. *
  38. * There are many different options for a directive.
  39. *
  40. * The difference resides in the return value of the factory function.
  41. * You can either return a "Directive Definition Object" (see below) that defines the directive properties,
  42. * or just the `postLink` function (all other properties will have the default values).
  43. *
  44. * <div class="alert alert-success">
  45. * **Best Practice:** It's recommended to use the "directive definition object" form.
  46. * </div>
  47. *
  48. * Here's an example directive declared with a Directive Definition Object:
  49. *
  50. * <pre>
  51. * var myModule = angular.module(...);
  52. *
  53. * myModule.directive('directiveName', function factory(injectables) {
  54. * var directiveDefinitionObject = {
  55. * priority: 0,
  56. * template: '<div></div>', // or // function(tElement, tAttrs) { ... },
  57. * // or
  58. * // templateUrl: 'directive.html', // or // function(tElement, tAttrs) { ... },
  59. * replace: false,
  60. * transclude: false,
  61. * restrict: 'A',
  62. * scope: false,
  63. * controller: function($scope, $element, $attrs, $transclude, otherInjectables) { ... },
  64. * require: 'siblingDirectiveName', // or // ['^parentDirectiveName', '?optionalDirectiveName', '?^optionalParent'],
  65. * compile: function compile(tElement, tAttrs, transclude) {
  66. * return {
  67. * pre: function preLink(scope, iElement, iAttrs, controller) { ... },
  68. * post: function postLink(scope, iElement, iAttrs, controller) { ... }
  69. * }
  70. * // or
  71. * // return function postLink( ... ) { ... }
  72. * },
  73. * // or
  74. * // link: {
  75. * // pre: function preLink(scope, iElement, iAttrs, controller) { ... },
  76. * // post: function postLink(scope, iElement, iAttrs, controller) { ... }
  77. * // }
  78. * // or
  79. * // link: function postLink( ... ) { ... }
  80. * };
  81. * return directiveDefinitionObject;
  82. * });
  83. * </pre>
  84. *
  85. * <div class="alert alert-warning">
  86. * **Note:** Any unspecified options will use the default value. You can see the default values below.
  87. * </div>
  88. *
  89. * Therefore the above can be simplified as:
  90. *
  91. * <pre>
  92. * var myModule = angular.module(...);
  93. *
  94. * myModule.directive('directiveName', function factory(injectables) {
  95. * var directiveDefinitionObject = {
  96. * link: function postLink(scope, iElement, iAttrs) { ... }
  97. * };
  98. * return directiveDefinitionObject;
  99. * // or
  100. * // return function postLink(scope, iElement, iAttrs) { ... }
  101. * });
  102. * </pre>
  103. *
  104. *
  105. *
  106. * ### Directive Definition Object
  107. *
  108. * The directive definition object provides instructions to the {@link api/ng.$compile
  109. * compiler}. The attributes are:
  110. *
  111. * #### `priority`
  112. * When there are multiple directives defined on a single DOM element, sometimes it
  113. * is necessary to specify the order in which the directives are applied. The `priority` is used
  114. * to sort the directives before their `compile` functions get called. Priority is defined as a
  115. * number. Directives with greater numerical `priority` are compiled first. Pre-link functions
  116. * are also run in priority order, but post-link functions are run in reverse order. The order
  117. * of directives with the same priority is undefined. The default priority is `0`.
  118. *
  119. * #### `terminal`
  120. * If set to true then the current `priority` will be the last set of directives
  121. * which will execute (any directives at the current priority will still execute
  122. * as the order of execution on same `priority` is undefined).
  123. *
  124. * #### `scope`
  125. * **If set to `true`,** then a new scope will be created for this directive. If multiple directives on the
  126. * same element request a new scope, only one new scope is created. The new scope rule does not
  127. * apply for the root of the template since the root of the template always gets a new scope.
  128. *
  129. * **If set to `{}` (object hash),** then a new "isolate" scope is created. The 'isolate' scope differs from
  130. * normal scope in that it does not prototypically inherit from the parent scope. This is useful
  131. * when creating reusable components, which should not accidentally read or modify data in the
  132. * parent scope.
  133. *
  134. * The 'isolate' scope takes an object hash which defines a set of local scope properties
  135. * derived from the parent scope. These local properties are useful for aliasing values for
  136. * templates. Locals definition is a hash of local scope property to its source:
  137. *
  138. * * `@` or `@attr` - bind a local scope property to the value of DOM attribute. The result is
  139. * always a string since DOM attributes are strings. If no `attr` name is specified then the
  140. * attribute name is assumed to be the same as the local name.
  141. * Given `<widget my-attr="hello {{name}}">` and widget definition
  142. * of `scope: { localName:'@myAttr' }`, then widget scope property `localName` will reflect
  143. * the interpolated value of `hello {{name}}`. As the `name` attribute changes so will the
  144. * `localName` property on the widget scope. The `name` is read from the parent scope (not
  145. * component scope).
  146. *
  147. * * `=` or `=attr` - set up bi-directional binding between a local scope property and the
  148. * parent scope property of name defined via the value of the `attr` attribute. If no `attr`
  149. * name is specified then the attribute name is assumed to be the same as the local name.
  150. * Given `<widget my-attr="parentModel">` and widget definition of
  151. * `scope: { localModel:'=myAttr' }`, then widget scope property `localModel` will reflect the
  152. * value of `parentModel` on the parent scope. Any changes to `parentModel` will be reflected
  153. * in `localModel` and any changes in `localModel` will reflect in `parentModel`. If the parent
  154. * scope property doesn't exist, it will throw a NON_ASSIGNABLE_MODEL_EXPRESSION exception. You
  155. * can avoid this behavior using `=?` or `=?attr` in order to flag the property as optional.
  156. *
  157. * * `&` or `&attr` - provides a way to execute an expression in the context of the parent scope.
  158. * If no `attr` name is specified then the attribute name is assumed to be the same as the
  159. * local name. Given `<widget my-attr="count = count + value">` and widget definition of
  160. * `scope: { localFn:'&myAttr' }`, then isolate scope property `localFn` will point to
  161. * a function wrapper for the `count = count + value` expression. Often it's desirable to
  162. * pass data from the isolated scope via an expression and to the parent scope, this can be
  163. * done by passing a map of local variable names and values into the expression wrapper fn.
  164. * For example, if the expression is `increment(amount)` then we can specify the amount value
  165. * by calling the `localFn` as `localFn({amount: 22})`.
  166. *
  167. *
  168. *
  169. * #### `controller`
  170. * Controller constructor function. The controller is instantiated before the
  171. * pre-linking phase and it is shared with other directives (see
  172. * `require` attribute). This allows the directives to communicate with each other and augment
  173. * each other's behavior. The controller is injectable (and supports bracket notation) with the following locals:
  174. *
  175. * * `$scope` - Current scope associated with the element
  176. * * `$element` - Current element
  177. * * `$attrs` - Current attributes object for the element
  178. * * `$transclude` - A transclude linking function pre-bound to the correct transclusion scope.
  179. * The scope can be overridden by an optional first argument.
  180. * `function([scope], cloneLinkingFn)`.
  181. *
  182. *
  183. * #### `require`
  184. * Require another directive and inject its controller as the fourth argument to the linking function. The
  185. * `require` takes a string name (or array of strings) of the directive(s) to pass in. If an array is used, the
  186. * injected argument will be an array in corresponding order. If no such directive can be
  187. * found, or if the directive does not have a controller, then an error is raised. The name can be prefixed with:
  188. *
  189. * * (no prefix) - Locate the required controller on the current element. Throw an error if not found.
  190. * * `?` - Attempt to locate the required controller or pass `null` to the `link` fn if not found.
  191. * * `^` - Locate the required controller by searching the element's parents. Throw an error if not found.
  192. * * `?^` - Attempt to locate the required controller by searching the element's parents or pass `null` to the
  193. * `link` fn if not found.
  194. *
  195. *
  196. * #### `controllerAs`
  197. * Controller alias at the directive scope. An alias for the controller so it
  198. * can be referenced at the directive template. The directive needs to define a scope for this
  199. * configuration to be used. Useful in the case when directive is used as component.
  200. *
  201. *
  202. * #### `restrict`
  203. * String of subset of `EACM` which restricts the directive to a specific directive
  204. * declaration style. If omitted, the default (attributes only) is used.
  205. *
  206. * * `E` - Element name: `<my-directive></my-directive>`
  207. * * `A` - Attribute (default): `<div my-directive="exp"></div>`
  208. * * `C` - Class: `<div class="my-directive: exp;"></div>`
  209. * * `M` - Comment: `<!-- directive: my-directive exp -->`
  210. *
  211. *
  212. * #### `template`
  213. * replace the current element with the contents of the HTML. The replacement process
  214. * migrates all of the attributes / classes from the old element to the new one. See the
  215. * {@link guide/directive#creating-custom-directives_creating-directives_template-expanding-directive
  216. * Directives Guide} for an example.
  217. *
  218. * You can specify `template` as a string representing the template or as a function which takes
  219. * two arguments `tElement` and `tAttrs` (described in the `compile` function api below) and
  220. * returns a string value representing the template.
  221. *
  222. *
  223. * #### `templateUrl`
  224. * Same as `template` but the template is loaded from the specified URL. Because
  225. * the template loading is asynchronous the compilation/linking is suspended until the template
  226. * is loaded.
  227. *
  228. * You can specify `templateUrl` as a string representing the URL or as a function which takes two
  229. * arguments `tElement` and `tAttrs` (described in the `compile` function api below) and returns
  230. * a string value representing the url. In either case, the template URL is passed through {@link
  231. * api/ng.$sce#methods_getTrustedResourceUrl $sce.getTrustedResourceUrl}.
  232. *
  233. *
  234. * #### `replace`
  235. * specify where the template should be inserted. Defaults to `false`.
  236. *
  237. * * `true` - the template will replace the current element.
  238. * * `false` - the template will replace the contents of the current element.
  239. *
  240. *
  241. * #### `transclude`
  242. * compile the content of the element and make it available to the directive.
  243. * Typically used with {@link api/ng.directive:ngTransclude
  244. * ngTransclude}. The advantage of transclusion is that the linking function receives a
  245. * transclusion function which is pre-bound to the correct scope. In a typical setup the widget
  246. * creates an `isolate` scope, but the transclusion is not a child, but a sibling of the `isolate`
  247. * scope. This makes it possible for the widget to have private state, and the transclusion to
  248. * be bound to the parent (pre-`isolate`) scope.
  249. *
  250. * * `true` - transclude the content of the directive.
  251. * * `'element'` - transclude the whole element including any directives defined at lower priority.
  252. *
  253. *
  254. * #### `compile`
  255. *
  256. * <pre>
  257. * function compile(tElement, tAttrs, transclude) { ... }
  258. * </pre>
  259. *
  260. * The compile function deals with transforming the template DOM. Since most directives do not do
  261. * template transformation, it is not used often. Examples that require compile functions are
  262. * directives that transform template DOM, such as {@link
  263. * api/ng.directive:ngRepeat ngRepeat}, or load the contents
  264. * asynchronously, such as {@link api/ngRoute.directive:ngView ngView}. The
  265. * compile function takes the following arguments.
  266. *
  267. * * `tElement` - template element - The element where the directive has been declared. It is
  268. * safe to do template transformation on the element and child elements only.
  269. *
  270. * * `tAttrs` - template attributes - Normalized list of attributes declared on this element shared
  271. * between all directive compile functions.
  272. *
  273. * * `transclude` - [*DEPRECATED*!] A transclude linking function: `function(scope, cloneLinkingFn)`
  274. *
  275. * <div class="alert alert-warning">
  276. * **Note:** The template instance and the link instance may be different objects if the template has
  277. * been cloned. For this reason it is **not** safe to do anything other than DOM transformations that
  278. * apply to all cloned DOM nodes within the compile function. Specifically, DOM listener registration
  279. * should be done in a linking function rather than in a compile function.
  280. * </div>
  281. *
  282. * <div class="alert alert-error">
  283. * **Note:** The `transclude` function that is passed to the compile function is deprecated, as it
  284. * e.g. does not know about the right outer scope. Please use the transclude function that is passed
  285. * to the link function instead.
  286. * </div>
  287. * A compile function can have a return value which can be either a function or an object.
  288. *
  289. * * returning a (post-link) function - is equivalent to registering the linking function via the
  290. * `link` property of the config object when the compile function is empty.
  291. *
  292. * * returning an object with function(s) registered via `pre` and `post` properties - allows you to
  293. * control when a linking function should be called during the linking phase. See info about
  294. * pre-linking and post-linking functions below.
  295. *
  296. *
  297. * #### `link`
  298. * This property is used only if the `compile` property is not defined.
  299. *
  300. * <pre>
  301. * function link(scope, iElement, iAttrs, controller, transcludeFn) { ... }
  302. * </pre>
  303. *
  304. * The link function is responsible for registering DOM listeners as well as updating the DOM. It is
  305. * executed after the template has been cloned. This is where most of the directive logic will be
  306. * put.
  307. *
  308. * * `scope` - {@link api/ng.$rootScope.Scope Scope} - The scope to be used by the
  309. * directive for registering {@link api/ng.$rootScope.Scope#methods_$watch watches}.
  310. *
  311. * * `iElement` - instance element - The element where the directive is to be used. It is safe to
  312. * manipulate the children of the element only in `postLink` function since the children have
  313. * already been linked.
  314. *
  315. * * `iAttrs` - instance attributes - Normalized list of attributes declared on this element shared
  316. * between all directive linking functions.
  317. *
  318. * * `controller` - a controller instance - A controller instance if at least one directive on the
  319. * element defines a controller. The controller is shared among all the directives, which allows
  320. * the directives to use the controllers as a communication channel.
  321. *
  322. * * `transcludeFn` - A transclude linking function pre-bound to the correct transclusion scope.
  323. * The scope can be overridden by an optional first argument. This is the same as the `$transclude`
  324. * parameter of directive controllers.
  325. * `function([scope], cloneLinkingFn)`.
  326. *
  327. *
  328. * #### Pre-linking function
  329. *
  330. * Executed before the child elements are linked. Not safe to do DOM transformation since the
  331. * compiler linking function will fail to locate the correct elements for linking.
  332. *
  333. * #### Post-linking function
  334. *
  335. * Executed after the child elements are linked. It is safe to do DOM transformation in the post-linking function.
  336. *
  337. * <a name="Attributes"></a>
  338. * ### Attributes
  339. *
  340. * The {@link api/ng.$compile.directive.Attributes Attributes} object - passed as a parameter in the
  341. * `link()` or `compile()` functions. It has a variety of uses.
  342. *
  343. * accessing *Normalized attribute names:*
  344. * Directives like 'ngBind' can be expressed in many ways: 'ng:bind', `data-ng-bind`, or 'x-ng-bind'.
  345. * the attributes object allows for normalized access to
  346. * the attributes.
  347. *
  348. * * *Directive inter-communication:* All directives share the same instance of the attributes
  349. * object which allows the directives to use the attributes object as inter directive
  350. * communication.
  351. *
  352. * * *Supports interpolation:* Interpolation attributes are assigned to the attribute object
  353. * allowing other directives to read the interpolated value.
  354. *
  355. * * *Observing interpolated attributes:* Use `$observe` to observe the value changes of attributes
  356. * that contain interpolation (e.g. `src="{{bar}}"`). Not only is this very efficient but it's also
  357. * the only way to easily get the actual value because during the linking phase the interpolation
  358. * hasn't been evaluated yet and so the value is at this time set to `undefined`.
  359. *
  360. * <pre>
  361. * function linkingFn(scope, elm, attrs, ctrl) {
  362. * // get the attribute value
  363. * console.log(attrs.ngModel);
  364. *
  365. * // change the attribute
  366. * attrs.$set('ngModel', 'new value');
  367. *
  368. * // observe changes to interpolated attribute
  369. * attrs.$observe('ngModel', function(value) {
  370. * console.log('ngModel has changed value to ' + value);
  371. * });
  372. * }
  373. * </pre>
  374. *
  375. * Below is an example using `$compileProvider`.
  376. *
  377. * <div class="alert alert-warning">
  378. * **Note**: Typically directives are registered with `module.directive`. The example below is
  379. * to illustrate how `$compile` works.
  380. * </div>
  381. *
  382. <doc:example module="compile">
  383. <doc:source>
  384. <script>
  385. angular.module('compile', [], function($compileProvider) {
  386. // configure new 'compile' directive by passing a directive
  387. // factory function. The factory function injects the '$compile'
  388. $compileProvider.directive('compile', function($compile) {
  389. // directive factory creates a link function
  390. return function(scope, element, attrs) {
  391. scope.$watch(
  392. function(scope) {
  393. // watch the 'compile' expression for changes
  394. return scope.$eval(attrs.compile);
  395. },
  396. function(value) {
  397. // when the 'compile' expression changes
  398. // assign it into the current DOM
  399. element.html(value);
  400. // compile the new DOM and link it to the current
  401. // scope.
  402. // NOTE: we only compile .childNodes so that
  403. // we don't get into infinite loop compiling ourselves
  404. $compile(element.contents())(scope);
  405. }
  406. );
  407. };
  408. })
  409. });
  410. function Ctrl($scope) {
  411. $scope.name = 'Angular';
  412. $scope.html = 'Hello {{name}}';
  413. }
  414. </script>
  415. <div ng-controller="Ctrl">
  416. <input ng-model="name"> <br>
  417. <textarea ng-model="html"></textarea> <br>
  418. <div compile="html"></div>
  419. </div>
  420. </doc:source>
  421. <doc:scenario>
  422. it('should auto compile', function() {
  423. expect(element('div[compile]').text()).toBe('Hello Angular');
  424. input('html').enter('{{name}}!');
  425. expect(element('div[compile]').text()).toBe('Angular!');
  426. });
  427. </doc:scenario>
  428. </doc:example>
  429. *
  430. *
  431. * @param {string|DOMElement} element Element or HTML string to compile into a template function.
  432. * @param {function(angular.Scope[, cloneAttachFn]} transclude function available to directives.
  433. * @param {number} maxPriority only apply directives lower then given priority (Only effects the
  434. * root element(s), not their children)
  435. * @returns {function(scope[, cloneAttachFn])} a link function which is used to bind template
  436. * (a DOM element/tree) to a scope. Where:
  437. *
  438. * * `scope` - A {@link ng.$rootScope.Scope Scope} to bind to.
  439. * * `cloneAttachFn` - If `cloneAttachFn` is provided, then the link function will clone the
  440. * `template` and call the `cloneAttachFn` function allowing the caller to attach the
  441. * cloned elements to the DOM document at the appropriate place. The `cloneAttachFn` is
  442. * called as: <br> `cloneAttachFn(clonedElement, scope)` where:
  443. *
  444. * * `clonedElement` - is a clone of the original `element` passed into the compiler.
  445. * * `scope` - is the current scope with which the linking function is working with.
  446. *
  447. * Calling the linking function returns the element of the template. It is either the original
  448. * element passed in, or the clone of the element if the `cloneAttachFn` is provided.
  449. *
  450. * After linking the view is not updated until after a call to $digest which typically is done by
  451. * Angular automatically.
  452. *
  453. * If you need access to the bound view, there are two ways to do it:
  454. *
  455. * - If you are not asking the linking function to clone the template, create the DOM element(s)
  456. * before you send them to the compiler and keep this reference around.
  457. * <pre>
  458. * var element = $compile('<p>{{total}}</p>')(scope);
  459. * </pre>
  460. *
  461. * - if on the other hand, you need the element to be cloned, the view reference from the original
  462. * example would not point to the clone, but rather to the original template that was cloned. In
  463. * this case, you can access the clone via the cloneAttachFn:
  464. * <pre>
  465. * var templateElement = angular.element('<p>{{total}}</p>'),
  466. * scope = ....;
  467. *
  468. * var clonedElement = $compile(templateElement)(scope, function(clonedElement, scope) {
  469. * //attach the clone to DOM document at the right place
  470. * });
  471. *
  472. * //now we have reference to the cloned DOM via `clonedElement`
  473. * </pre>
  474. *
  475. *
  476. * For information on how the compiler works, see the
  477. * {@link guide/compiler Angular HTML Compiler} section of the Developer Guide.
  478. */
  479. var $compileMinErr = minErr('$compile');
  480. /**
  481. * @ngdoc service
  482. * @name ng.$compileProvider
  483. * @function
  484. *
  485. * @description
  486. */
  487. $CompileProvider.$inject = ['$provide', '$$sanitizeUriProvider'];
  488. function $CompileProvider($provide, $$sanitizeUriProvider) {
  489. var hasDirectives = {},
  490. Suffix = 'Directive',
  491. COMMENT_DIRECTIVE_REGEXP = /^\s*directive\:\s*([\d\w\-_]+)\s+(.*)$/,
  492. CLASS_DIRECTIVE_REGEXP = /(([\d\w\-_]+)(?:\:([^;]+))?;?)/;
  493. // Ref: http://developers.whatwg.org/webappapis.html#event-handler-idl-attributes
  494. // The assumption is that future DOM event attribute names will begin with
  495. // 'on' and be composed of only English letters.
  496. var EVENT_HANDLER_ATTR_REGEXP = /^(on[a-z]+|formaction)$/;
  497. /**
  498. * @ngdoc function
  499. * @name ng.$compileProvider#directive
  500. * @methodOf ng.$compileProvider
  501. * @function
  502. *
  503. * @description
  504. * Register a new directive with the compiler.
  505. *
  506. * @param {string|Object} name Name of the directive in camel-case (i.e. <code>ngBind</code> which
  507. * will match as <code>ng-bind</code>), or an object map of directives where the keys are the
  508. * names and the values are the factories.
  509. * @param {function|Array} directiveFactory An injectable directive factory function. See
  510. * {@link guide/directive} for more info.
  511. * @returns {ng.$compileProvider} Self for chaining.
  512. */
  513. this.directive = function registerDirective(name, directiveFactory) {
  514. assertNotHasOwnProperty(name, 'directive');
  515. if (isString(name)) {
  516. assertArg(directiveFactory, 'directiveFactory');
  517. if (!hasDirectives.hasOwnProperty(name)) {
  518. hasDirectives[name] = [];
  519. $provide.factory(name + Suffix, ['$injector', '$exceptionHandler',
  520. function($injector, $exceptionHandler) {
  521. var directives = [];
  522. forEach(hasDirectives[name], function(directiveFactory, index) {
  523. try {
  524. var directive = $injector.invoke(directiveFactory);
  525. if (isFunction(directive)) {
  526. directive = { compile: valueFn(directive) };
  527. } else if (!directive.compile && directive.link) {
  528. directive.compile = valueFn(directive.link);
  529. }
  530. directive.priority = directive.priority || 0;
  531. directive.index = index;
  532. directive.name = directive.name || name;
  533. directive.require = directive.require || (directive.controller && directive.name);
  534. directive.restrict = directive.restrict || 'A';
  535. directives.push(directive);
  536. } catch (e) {
  537. $exceptionHandler(e);
  538. }
  539. });
  540. return directives;
  541. }]);
  542. }
  543. hasDirectives[name].push(directiveFactory);
  544. } else {
  545. forEach(name, reverseParams(registerDirective));
  546. }
  547. return this;
  548. };
  549. /**
  550. * @ngdoc function
  551. * @name ng.$compileProvider#aHrefSanitizationWhitelist
  552. * @methodOf ng.$compileProvider
  553. * @function
  554. *
  555. * @description
  556. * Retrieves or overrides the default regular expression that is used for whitelisting of safe
  557. * urls during a[href] sanitization.
  558. *
  559. * The sanitization is a security measure aimed at prevent XSS attacks via html links.
  560. *
  561. * Any url about to be assigned to a[href] via data-binding is first normalized and turned into
  562. * an absolute url. Afterwards, the url is matched against the `aHrefSanitizationWhitelist`
  563. * regular expression. If a match is found, the original url is written into the dom. Otherwise,
  564. * the absolute url is prefixed with `'unsafe:'` string and only then is it written into the DOM.
  565. *
  566. * @param {RegExp=} regexp New regexp to whitelist urls with.
  567. * @returns {RegExp|ng.$compileProvider} Current RegExp if called without value or self for
  568. * chaining otherwise.
  569. */
  570. this.aHrefSanitizationWhitelist = function(regexp) {
  571. if (isDefined(regexp)) {
  572. $$sanitizeUriProvider.aHrefSanitizationWhitelist(regexp);
  573. return this;
  574. } else {
  575. return $$sanitizeUriProvider.aHrefSanitizationWhitelist();
  576. }
  577. };
  578. /**
  579. * @ngdoc function
  580. * @name ng.$compileProvider#imgSrcSanitizationWhitelist
  581. * @methodOf ng.$compileProvider
  582. * @function
  583. *
  584. * @description
  585. * Retrieves or overrides the default regular expression that is used for whitelisting of safe
  586. * urls during img[src] sanitization.
  587. *
  588. * The sanitization is a security measure aimed at prevent XSS attacks via html links.
  589. *
  590. * Any url about to be assigned to img[src] via data-binding is first normalized and turned into
  591. * an absolute url. Afterwards, the url is matched against the `imgSrcSanitizationWhitelist`
  592. * regular expression. If a match is found, the original url is written into the dom. Otherwise,
  593. * the absolute url is prefixed with `'unsafe:'` string and only then is it written into the DOM.
  594. *
  595. * @param {RegExp=} regexp New regexp to whitelist urls with.
  596. * @returns {RegExp|ng.$compileProvider} Current RegExp if called without value or self for
  597. * chaining otherwise.
  598. */
  599. this.imgSrcSanitizationWhitelist = function(regexp) {
  600. if (isDefined(regexp)) {
  601. $$sanitizeUriProvider.imgSrcSanitizationWhitelist(regexp);
  602. return this;
  603. } else {
  604. return $$sanitizeUriProvider.imgSrcSanitizationWhitelist();
  605. }
  606. };
  607. this.$get = [
  608. '$injector', '$interpolate', '$exceptionHandler', '$http', '$templateCache', '$parse',
  609. '$controller', '$rootScope', '$document', '$sce', '$animate', '$$sanitizeUri',
  610. function($injector, $interpolate, $exceptionHandler, $http, $templateCache, $parse,
  611. $controller, $rootScope, $document, $sce, $animate, $$sanitizeUri) {
  612. var Attributes = function(element, attr) {
  613. this.$$element = element;
  614. this.$attr = attr || {};
  615. };
  616. Attributes.prototype = {
  617. $normalize: directiveNormalize,
  618. /**
  619. * @ngdoc function
  620. * @name ng.$compile.directive.Attributes#$addClass
  621. * @methodOf ng.$compile.directive.Attributes
  622. * @function
  623. *
  624. * @description
  625. * Adds the CSS class value specified by the classVal parameter to the element. If animations
  626. * are enabled then an animation will be triggered for the class addition.
  627. *
  628. * @param {string} classVal The className value that will be added to the element
  629. */
  630. $addClass : function(classVal) {
  631. if(classVal && classVal.length > 0) {
  632. $animate.addClass(this.$$element, classVal);
  633. }
  634. },
  635. /**
  636. * @ngdoc function
  637. * @name ng.$compile.directive.Attributes#$removeClass
  638. * @methodOf ng.$compile.directive.Attributes
  639. * @function
  640. *
  641. * @description
  642. * Removes the CSS class value specified by the classVal parameter from the element. If
  643. * animations are enabled then an animation will be triggered for the class removal.
  644. *
  645. * @param {string} classVal The className value that will be removed from the element
  646. */
  647. $removeClass : function(classVal) {
  648. if(classVal && classVal.length > 0) {
  649. $animate.removeClass(this.$$element, classVal);
  650. }
  651. },
  652. /**
  653. * @ngdoc function
  654. * @name ng.$compile.directive.Attributes#$updateClass
  655. * @methodOf ng.$compile.directive.Attributes
  656. * @function
  657. *
  658. * @description
  659. * Adds and removes the appropriate CSS class values to the element based on the difference
  660. * between the new and old CSS class values (specified as newClasses and oldClasses).
  661. *
  662. * @param {string} newClasses The current CSS className value
  663. * @param {string} oldClasses The former CSS className value
  664. */
  665. $updateClass : function(newClasses, oldClasses) {
  666. this.$removeClass(tokenDifference(oldClasses, newClasses));
  667. this.$addClass(tokenDifference(newClasses, oldClasses));
  668. },
  669. /**
  670. * Set a normalized attribute on the element in a way such that all directives
  671. * can share the attribute. This function properly handles boolean attributes.
  672. * @param {string} key Normalized key. (ie ngAttribute)
  673. * @param {string|boolean} value The value to set. If `null` attribute will be deleted.
  674. * @param {boolean=} writeAttr If false, does not write the value to DOM element attribute.
  675. * Defaults to true.
  676. * @param {string=} attrName Optional none normalized name. Defaults to key.
  677. */
  678. $set: function(key, value, writeAttr, attrName) {
  679. // TODO: decide whether or not to throw an error if "class"
  680. //is set through this function since it may cause $updateClass to
  681. //become unstable.
  682. var booleanKey = getBooleanAttrName(this.$$element[0], key),
  683. normalizedVal,
  684. nodeName;
  685. if (booleanKey) {
  686. this.$$element.prop(key, value);
  687. attrName = booleanKey;
  688. }
  689. this[key] = value;
  690. // translate normalized key to actual key
  691. if (attrName) {
  692. this.$attr[key] = attrName;
  693. } else {
  694. attrName = this.$attr[key];
  695. if (!attrName) {
  696. this.$attr[key] = attrName = snake_case(key, '-');
  697. }
  698. }
  699. nodeName = nodeName_(this.$$element);
  700. // sanitize a[href] and img[src] values
  701. if ((nodeName === 'A' && key === 'href') ||
  702. (nodeName === 'IMG' && key === 'src')) {
  703. this[key] = value = $$sanitizeUri(value, key === 'src');
  704. }
  705. if (writeAttr !== false) {
  706. if (value === null || value === undefined) {
  707. this.$$element.removeAttr(attrName);
  708. } else {
  709. this.$$element.attr(attrName, value);
  710. }
  711. }
  712. // fire observers
  713. var $$observers = this.$$observers;
  714. $$observers && forEach($$observers[key], function(fn) {
  715. try {
  716. fn(value);
  717. } catch (e) {
  718. $exceptionHandler(e);
  719. }
  720. });
  721. },
  722. /**
  723. * @ngdoc function
  724. * @name ng.$compile.directive.Attributes#$observe
  725. * @methodOf ng.$compile.directive.Attributes
  726. * @function
  727. *
  728. * @description
  729. * Observes an interpolated attribute.
  730. *
  731. * The observer function will be invoked once during the next `$digest` following
  732. * compilation. The observer is then invoked whenever the interpolated value
  733. * changes.
  734. *
  735. * @param {string} key Normalized key. (ie ngAttribute) .
  736. * @param {function(interpolatedValue)} fn Function that will be called whenever
  737. the interpolated value of the attribute changes.
  738. * See the {@link guide/directive#Attributes Directives} guide for more info.
  739. * @returns {function()} the `fn` parameter.
  740. */
  741. $observe: function(key, fn) {
  742. var attrs = this,
  743. $$observers = (attrs.$$observers || (attrs.$$observers = {})),
  744. listeners = ($$observers[key] || ($$observers[key] = []));
  745. listeners.push(fn);
  746. $rootScope.$evalAsync(function() {
  747. if (!listeners.$$inter) {
  748. // no one registered attribute interpolation function, so lets call it manually
  749. fn(attrs[key]);
  750. }
  751. });
  752. return fn;
  753. }
  754. };
  755. var startSymbol = $interpolate.startSymbol(),
  756. endSymbol = $interpolate.endSymbol(),
  757. denormalizeTemplate = (startSymbol == '{{' || endSymbol == '}}')
  758. ? identity
  759. : function denormalizeTemplate(template) {
  760. return template.replace(/\{\{/g, startSymbol).replace(/}}/g, endSymbol);
  761. },
  762. NG_ATTR_BINDING = /^ngAttr[A-Z]/;
  763. return compile;
  764. //================================
  765. function compile($compileNodes, transcludeFn, maxPriority, ignoreDirective,
  766. previousCompileContext) {
  767. if (!($compileNodes instanceof jqLite)) {
  768. // jquery always rewraps, whereas we need to preserve the original selector so that we can
  769. // modify it.
  770. $compileNodes = jqLite($compileNodes);
  771. }
  772. // We can not compile top level text elements since text nodes can be merged and we will
  773. // not be able to attach scope data to them, so we will wrap them in <span>
  774. forEach($compileNodes, function(node, index){
  775. if (node.nodeType == 3 /* text node */ && node.nodeValue.match(/\S+/) /* non-empty */ ) {
  776. $compileNodes[index] = node = jqLite(node).wrap('<span></span>').parent()[0];
  777. }
  778. });
  779. var compositeLinkFn =
  780. compileNodes($compileNodes, transcludeFn, $compileNodes,
  781. maxPriority, ignoreDirective, previousCompileContext);
  782. safeAddClass($compileNodes, 'ng-scope');
  783. return function publicLinkFn(scope, cloneConnectFn, transcludeControllers){
  784. assertArg(scope, 'scope');
  785. // important!!: we must call our jqLite.clone() since the jQuery one is trying to be smart
  786. // and sometimes changes the structure of the DOM.
  787. var $linkNode = cloneConnectFn
  788. ? JQLitePrototype.clone.call($compileNodes) // IMPORTANT!!!
  789. : $compileNodes;
  790. forEach(transcludeControllers, function(instance, name) {
  791. $linkNode.data('$' + name + 'Controller', instance);
  792. });
  793. // Attach scope only to non-text nodes.
  794. for(var i = 0, ii = $linkNode.length; i<ii; i++) {
  795. var node = $linkNode[i],
  796. nodeType = node.nodeType;
  797. if (nodeType === 1 /* element */ || nodeType === 9 /* document */) {
  798. $linkNode.eq(i).data('$scope', scope);
  799. }
  800. }
  801. if (cloneConnectFn) cloneConnectFn($linkNode, scope);
  802. if (compositeLinkFn) compositeLinkFn(scope, $linkNode, $linkNode);
  803. return $linkNode;
  804. };
  805. }
  806. function safeAddClass($element, className) {
  807. try {
  808. $element.addClass(className);
  809. } catch(e) {
  810. // ignore, since it means that we are trying to set class on
  811. // SVG element, where class name is read-only.
  812. }
  813. }
  814. /**
  815. * Compile function matches each node in nodeList against the directives. Once all directives
  816. * for a particular node are collected their compile functions are executed. The compile
  817. * functions return values - the linking functions - are combined into a composite linking
  818. * function, which is the a linking function for the node.
  819. *
  820. * @param {NodeList} nodeList an array of nodes or NodeList to compile
  821. * @param {function(angular.Scope[, cloneAttachFn]} transcludeFn A linking function, where the
  822. * scope argument is auto-generated to the new child of the transcluded parent scope.
  823. * @param {DOMElement=} $rootElement If the nodeList is the root of the compilation tree then
  824. * the rootElement must be set the jqLite collection of the compile root. This is
  825. * needed so that the jqLite collection items can be replaced with widgets.
  826. * @param {number=} maxPriority Max directive priority.
  827. * @returns {?function} A composite linking function of all of the matched directives or null.
  828. */
  829. function compileNodes(nodeList, transcludeFn, $rootElement, maxPriority, ignoreDirective,
  830. previousCompileContext) {
  831. var linkFns = [],
  832. attrs, directives, nodeLinkFn, childNodes, childLinkFn, linkFnFound;
  833. for (var i = 0; i < nodeList.length; i++) {
  834. attrs = new Attributes();
  835. // we must always refer to nodeList[i] since the nodes can be replaced underneath us.
  836. directives = collectDirectives(nodeList[i], [], attrs, i === 0 ? maxPriority : undefined,
  837. ignoreDirective);
  838. nodeLinkFn = (directives.length)
  839. ? applyDirectivesToNode(directives, nodeList[i], attrs, transcludeFn, $rootElement,
  840. null, [], [], previousCompileContext)
  841. : null;
  842. if (nodeLinkFn && nodeLinkFn.scope) {
  843. safeAddClass(jqLite(nodeList[i]), 'ng-scope');
  844. }
  845. childLinkFn = (nodeLinkFn && nodeLinkFn.terminal ||
  846. !(childNodes = nodeList[i].childNodes) ||
  847. !childNodes.length)
  848. ? null
  849. : compileNodes(childNodes,
  850. nodeLinkFn ? nodeLinkFn.transclude : transcludeFn);
  851. linkFns.push(nodeLinkFn, childLinkFn);
  852. linkFnFound = linkFnFound || nodeLinkFn || childLinkFn;
  853. //use the previous context only for the first element in the virtual group
  854. previousCompileContext = null;
  855. }
  856. // return a linking function if we have found anything, null otherwise
  857. return linkFnFound ? compositeLinkFn : null;
  858. function compositeLinkFn(scope, nodeList, $rootElement, boundTranscludeFn) {
  859. var nodeLinkFn, childLinkFn, node, $node, childScope, childTranscludeFn, i, ii, n;
  860. // copy nodeList so that linking doesn't break due to live list updates.
  861. var nodeListLength = nodeList.length,
  862. stableNodeList = new Array(nodeListLength);
  863. for (i = 0; i < nodeListLength; i++) {
  864. stableNodeList[i] = nodeList[i];
  865. }
  866. for(i = 0, n = 0, ii = linkFns.length; i < ii; n++) {
  867. node = stableNodeList[n];
  868. nodeLinkFn = linkFns[i++];
  869. childLinkFn = linkFns[i++];
  870. $node = jqLite(node);
  871. if (nodeLinkFn) {
  872. if (nodeLinkFn.scope) {
  873. childScope = scope.$new();
  874. $node.data('$scope', childScope);
  875. } else {
  876. childScope = scope;
  877. }
  878. childTranscludeFn = nodeLinkFn.transclude;
  879. if (childTranscludeFn || (!boundTranscludeFn && transcludeFn)) {
  880. nodeLinkFn(childLinkFn, childScope, node, $rootElement,
  881. createBoundTranscludeFn(scope, childTranscludeFn || transcludeFn)
  882. );
  883. } else {
  884. nodeLinkFn(childLinkFn, childScope, node, $rootElement, boundTranscludeFn);
  885. }
  886. } else if (childLinkFn) {
  887. childLinkFn(scope, node.childNodes, undefined, boundTranscludeFn);
  888. }
  889. }
  890. }
  891. }
  892. function createBoundTranscludeFn(scope, transcludeFn) {
  893. return function boundTranscludeFn(transcludedScope, cloneFn, controllers) {
  894. var scopeCreated = false;
  895. if (!transcludedScope) {
  896. transcludedScope = scope.$new();
  897. transcludedScope.$$transcluded = true;
  898. scopeCreated = true;
  899. }
  900. var clone = transcludeFn(transcludedScope, cloneFn, controllers);
  901. if (scopeCreated) {
  902. clone.on('$destroy', bind(transcludedScope, transcludedScope.$destroy));
  903. }
  904. return clone;
  905. };
  906. }
  907. /**
  908. * Looks for directives on the given node and adds them to the directive collection which is
  909. * sorted.
  910. *
  911. * @param node Node to search.
  912. * @param directives An array to which the directives are added to. This array is sorted before
  913. * the function returns.
  914. * @param attrs The shared attrs object which is used to populate the normalized attributes.
  915. * @param {number=} maxPriority Max directive priority.
  916. */
  917. function collectDirectives(node, directives, attrs, maxPriority, ignoreDirective) {
  918. var nodeType = node.nodeType,
  919. attrsMap = attrs.$attr,
  920. match,
  921. className;
  922. switch(nodeType) {
  923. case 1: /* Element */
  924. // use the node name: <directive>
  925. addDirective(directives,
  926. directiveNormalize(nodeName_(node).toLowerCase()), 'E', maxPriority, ignoreDirective);
  927. // iterate over the attributes
  928. for (var attr, name, nName, ngAttrName, value, nAttrs = node.attributes,
  929. j = 0, jj = nAttrs && nAttrs.length; j < jj; j++) {
  930. var attrStartName = false;
  931. var attrEndName = false;
  932. attr = nAttrs[j];
  933. if (!msie || msie >= 8 || attr.specified) {
  934. name = attr.name;
  935. // support ngAttr attribute binding
  936. ngAttrName = directiveNormalize(name);
  937. if (NG_ATTR_BINDING.test(ngAttrName)) {
  938. name = snake_case(ngAttrName.substr(6), '-');
  939. }
  940. var directiveNName = ngAttrName.replace(/(Start|End)$/, '');
  941. if (ngAttrName === directiveNName + 'Start') {
  942. attrStartName = name;
  943. attrEndName = name.substr(0, name.length - 5) + 'end';
  944. name = name.substr(0, name.length - 6);
  945. }
  946. nName = directiveNormalize(name.toLowerCase());
  947. attrsMap[nName] = name;
  948. attrs[nName] = value = trim(attr.value);
  949. if (getBooleanAttrName(node, nName)) {
  950. attrs[nName] = true; // presence means true
  951. }
  952. addAttrInterpolateDirective(node, directives, value, nName);
  953. addDirective(directives, nName, 'A', maxPriority, ignoreDirective, attrStartName,
  954. attrEndName);
  955. }
  956. }
  957. // use class as directive
  958. className = node.className;
  959. if (isString(className) && className !== '') {
  960. while (match = CLASS_DIRECTIVE_REGEXP.exec(className)) {
  961. nName = directiveNormalize(match[2]);
  962. if (addDirective(directives, nName, 'C', maxPriority, ignoreDirective)) {
  963. attrs[nName] = trim(match[3]);
  964. }
  965. className = className.substr(match.index + match[0].length);
  966. }
  967. }
  968. break;
  969. case 3: /* Text Node */
  970. addTextInterpolateDirective(directives, node.nodeValue);
  971. break;
  972. case 8: /* Comment */
  973. try {
  974. match = COMMENT_DIRECTIVE_REGEXP.exec(node.nodeValue);
  975. if (match) {
  976. nName = directiveNormalize(match[1]);
  977. if (addDirective(directives, nName, 'M', maxPriority, ignoreDirective)) {
  978. attrs[nName] = trim(match[2]);
  979. }
  980. }
  981. } catch (e) {
  982. // turns out that under some circumstances IE9 throws errors when one attempts to read
  983. // comment's node value.
  984. // Just ignore it and continue. (Can't seem to reproduce in test case.)
  985. }
  986. break;
  987. }
  988. directives.sort(byPriority);
  989. return directives;
  990. }
  991. /**
  992. * Given a node with an directive-start it collects all of the siblings until it finds
  993. * directive-end.
  994. * @param node
  995. * @param attrStart
  996. * @param attrEnd
  997. * @returns {*}
  998. */
  999. function groupScan(node, attrStart, attrEnd) {
  1000. var nodes = [];
  1001. var depth = 0;
  1002. if (attrStart && node.hasAttribute && node.hasAttribute(attrStart)) {
  1003. var startNode = node;
  1004. do {
  1005. if (!node) {
  1006. throw $compileMinErr('uterdir',
  1007. "Unterminated attribute, found '{0}' but no matching '{1}' found.",
  1008. attrStart, attrEnd);
  1009. }
  1010. if (node.nodeType == 1 /** Element **/) {
  1011. if (node.hasAttribute(attrStart)) depth++;
  1012. if (node.hasAttribute(attrEnd)) depth--;
  1013. }
  1014. nodes.push(node);
  1015. node = node.nextSibling;
  1016. } while (depth > 0);
  1017. } else {
  1018. nodes.push(node);
  1019. }
  1020. return jqLite(nodes);
  1021. }
  1022. /**
  1023. * Wrapper for linking function which converts normal linking function into a grouped
  1024. * linking function.
  1025. * @param linkFn
  1026. * @param attrStart
  1027. * @param attrEnd
  1028. * @returns {Function}
  1029. */
  1030. function groupElementsLinkFnWrapper(linkFn, attrStart, attrEnd) {
  1031. return function(scope, element, attrs, controllers, transcludeFn) {
  1032. element = groupScan(element[0], attrStart, attrEnd);
  1033. return linkFn(scope, element, attrs, controllers, transcludeFn);
  1034. };
  1035. }
  1036. /**
  1037. * Once the directives have been collected, their compile functions are executed. This method
  1038. * is responsible for inlining directive templates as well as terminating the application
  1039. * of the directives if the terminal directive has been reached.
  1040. *
  1041. * @param {Array} directives Array of collected directives to execute their compile function.
  1042. * this needs to be pre-sorted by priority order.
  1043. * @param {Node} compileNode The raw DOM node to apply the compile functions to
  1044. * @param {Object} templateAttrs The shared attribute function
  1045. * @param {function(angular.Scope[, cloneAttachFn]} transcludeFn A linking function, where the
  1046. * scope argument is auto-generated to the new
  1047. * child of the transcluded parent scope.
  1048. * @param {JQLite} jqCollection If we are working on the root of the compile tree then this
  1049. * argument has the root jqLite array so that we can replace nodes
  1050. * on it.
  1051. * @param {Object=} originalReplaceDirective An optional directive that will be ignored when
  1052. * compiling the transclusion.
  1053. * @param {Array.<Function>} preLinkFns
  1054. * @param {Array.<Function>} postLinkFns
  1055. * @param {Object} previousCompileContext Context used for previous compilation of the current
  1056. * node
  1057. * @returns linkFn
  1058. */
  1059. function applyDirectivesToNode(directives, compileNode, templateAttrs, transcludeFn,
  1060. jqCollection, originalReplaceDirective, preLinkFns, postLinkFns,
  1061. previousCompileContext) {
  1062. previousCompileContext = previousCompileContext || {};
  1063. var terminalPriority = -Number.MAX_VALUE,
  1064. newScopeDirective,
  1065. controllerDirectives = previousCompileContext.controllerDirectives,
  1066. newIsolateScopeDirective = previousCompileContext.newIsolateScopeDirective,
  1067. templateDirective = previousCompileContext.templateDirective,
  1068. nonTlbTranscludeDirective = previousCompileContext.nonTlbTranscludeDirective,
  1069. hasTranscludeDirective = false,
  1070. hasElementTranscludeDirective = false,
  1071. $compileNode = templateAttrs.$$element = jqLite(compileNode),
  1072. directive,
  1073. directiveName,
  1074. $template,
  1075. replaceDirective = originalReplaceDirective,
  1076. childTranscludeFn = transcludeFn,
  1077. linkFn,
  1078. directiveValue;
  1079. // executes all directives on the current element
  1080. for(var i = 0, ii = directives.length; i < ii; i++) {
  1081. directive = directives[i];
  1082. var attrStart = directive.$$start;
  1083. var attrEnd = directive.$$end;
  1084. // collect multiblock sections
  1085. if (attrStart) {
  1086. $compileNode = groupScan(compileNode, attrStart, attrEnd);
  1087. }
  1088. $template = undefined;
  1089. if (terminalPriority > directive.priority) {
  1090. break; // prevent further processing of directives
  1091. }
  1092. if (directiveValue = directive.scope) {
  1093. newScopeDirective = newScopeDirective || directive;
  1094. // skip the check for directives with async templates, we'll check the derived sync
  1095. // directive when the template arrives
  1096. if (!directive.templateUrl) {
  1097. assertNoDuplicate('new/isolated scope', newIsolateScopeDirective, directive,
  1098. $compileNode);
  1099. if (isObject(directiveValue)) {
  1100. newIsolateScopeDirective = directive;
  1101. }
  1102. }
  1103. }
  1104. directiveName = directive.name;
  1105. if (!directive.templateUrl && directive.controller) {
  1106. directiveValue = directive.controller;
  1107. controllerDirectives = controllerDirectives || {};
  1108. assertNoDuplicate("'" + directiveName + "' controller",
  1109. controllerDirectives[directiveName], directive, $compileNode);
  1110. controllerDirectives[directiveName] = directive;
  1111. }
  1112. if (directiveValue = directive.transclude) {
  1113. hasTranscludeDirective = true;
  1114. // Special case ngIf and ngRepeat so that we don't complain about duplicate transclusion.
  1115. // This option should only be used by directives that know how to how to safely handle element transclusion,
  1116. // where the transcluded nodes are added or replaced after linking.
  1117. if (!directive.$$tlb) {
  1118. assertNoDuplicate('transclusion', nonTlbTranscludeDirective, directive, $compileNode);
  1119. nonTlbTranscludeDirective = directive;
  1120. }
  1121. if (directiveValue == 'element') {
  1122. hasElementTranscludeDirective = true;
  1123. terminalPriority = directive.priority;
  1124. $template = groupScan(compileNode, attrStart, attrEnd);
  1125. $compileNode = templateAttrs.$$element =
  1126. jqLite(document.createComment(' ' + directiveName + ': ' +
  1127. templateAttrs[directiveName] + ' '));
  1128. compileNode = $compileNode[0];
  1129. replaceWith(jqCollection, jqLite(sliceArgs($template)), compileNode);
  1130. childTranscludeFn = compile($template, transcludeFn, terminalPriority,
  1131. replaceDirective && replaceDirective.name, {
  1132. // Don't pass in:
  1133. // - controllerDirectives - otherwise we'll create duplicates controllers
  1134. // - newIsolateScopeDirective or templateDirective - combining templates with
  1135. // element transclusion doesn't make sense.
  1136. //
  1137. // We need only nonTlbTranscludeDirective so that we prevent putting transclusion
  1138. // on the same element more than once.
  1139. nonTlbTranscludeDirective: nonTlbTranscludeDirective
  1140. });
  1141. } else {
  1142. $template = jqLite(jqLiteClone(compileNode)).contents();
  1143. $compileNode.empty(); // clear contents
  1144. childTranscludeFn = compile($template, transcludeFn);
  1145. }
  1146. }
  1147. if (directive.template) {
  1148. assertNoDuplicate('template', templateDirective, directive, $compileNode);
  1149. templateDirective = directive;
  1150. directiveValue = (isFunction(directive.template))
  1151. ? directive.template($compileNode, templateAttrs)
  1152. : directive.template;
  1153. directiveValue = denormalizeTemplate(directiveValue);
  1154. if (directive.replace) {
  1155. replaceDirective = directive;
  1156. $template = jqLite('<div>' +
  1157. trim(directiveValue) +
  1158. '</div>').contents();
  1159. compileNode = $template[0];
  1160. if ($template.length != 1 || compileNode.nodeType !== 1) {
  1161. throw $compileMinErr('tplrt',
  1162. "Template for directive '{0}' must have exactly one root element. {1}",
  1163. directiveName, '');
  1164. }
  1165. replaceWith(jqCollection, $compileNode, compileNode);
  1166. var newTemplateAttrs = {$attr: {}};
  1167. // combine directives from the original node and from the template:
  1168. // - take the array of directives for this element
  1169. // - split it into two parts, those that already applied (processed) and those that weren't (unprocessed)
  1170. // - collect directives from the template and sort them by priority
  1171. // - combine directives as: processed + template + unprocessed
  1172. var templateDirectives = collectDirectives(compileNode, [], newTemplateAttrs);
  1173. var unprocessedDirectives = directives.splice(i + 1, directives.length - (i + 1));
  1174. if (newIsolateScopeDirective) {
  1175. markDirectivesAsIsolate(templateDirectives);
  1176. }
  1177. directives = directives.concat(templateDirectives).concat(unprocessedDirectives);
  1178. mergeTemplateAttributes(templateAttrs, newTemplateAttrs);
  1179. ii = directives.length;
  1180. } else {
  1181. $compileNode.html(directiveValue);
  1182. }
  1183. }
  1184. if (directive.templateUrl) {
  1185. assertNoDuplicate('template', templateDirective, directive, $compileNode);
  1186. templateDirective = directive;
  1187. if (directive.replace) {
  1188. replaceDirective = directive;
  1189. }
  1190. nodeLinkFn = compileTemplateUrl(directives.splice(i, directives.length - i), $compileNode,
  1191. templateAttrs, jqCollection, childTranscludeFn, preLinkFns, postLinkFns, {
  1192. controllerDirectives: controllerDirectives,
  1193. newIsolateScopeDirective: newIsolateScopeDirective,
  1194. templateDirective: templateDirective,
  1195. nonTlbTranscludeDirective: nonTlbTranscludeDirective
  1196. });
  1197. ii = directives.length;
  1198. } else if (directive.compile) {
  1199. try {
  1200. linkFn = directive.compile($compileNode, templateAttrs, childTranscludeFn);
  1201. if (isFunction(linkFn)) {
  1202. addLinkFns(null, linkFn, attrStart, attrEnd);
  1203. } else if (linkFn) {
  1204. addLinkFns(linkFn.pre, linkFn.post, attrStart, attrEnd);
  1205. }
  1206. } catch (e) {
  1207. $exceptionHandler(e, startingTag($compileNode));
  1208. }
  1209. }
  1210. if (directive.terminal) {
  1211. nodeLinkFn.terminal = true;
  1212. terminalPriority = Math.max(terminalPriority, directive.priority);
  1213. }
  1214. }
  1215. nodeLinkFn.scope = newScopeDirective && newScopeDirective.scope === true;
  1216. nodeLinkFn.transclude = hasTranscludeDirective && childTranscludeFn;
  1217. // might be normal or delayed nodeLinkFn depending on if templateUrl is present
  1218. return nodeLinkFn;
  1219. ////////////////////
  1220. function addLinkFns(pre, post, attrStart, attrEnd) {
  1221. if (pre) {
  1222. if (attrStart) pre = groupElementsLinkFnWrapper(pre, attrStart, attrEnd);
  1223. pre.require = directive.require;
  1224. if (newIsolateScopeDirective === directive || directive.$$isolateScope) {
  1225. pre = cloneAndAnnotateFn(pre, {isolateScope: true});
  1226. }
  1227. preLinkFns.push(pre);
  1228. }
  1229. if (post) {
  1230. if (attrStart) post = groupElementsLinkFnWrapper(post, attrStart, attrEnd);
  1231. post.require = directive.require;
  1232. if (newIsolateScopeDirective === directive || directive.$$isolateScope) {
  1233. post = cloneAndAnnotateFn(post, {isolateScope: true});
  1234. }
  1235. postLinkFns.push(post);
  1236. }
  1237. }
  1238. function getControllers(require, $element, elementControllers) {
  1239. var value, retrievalMethod = 'data', optional = false;
  1240. if (isString(require)) {
  1241. while((value = require.charAt(0)) == '^' || value == '?') {
  1242. require = require.substr(1);
  1243. if (value == '^') {
  1244. retrievalMethod = 'inheritedData';
  1245. }
  1246. optional = optional || value == '?';
  1247. }
  1248. value = null;
  1249. if (elementControllers && retrievalMethod === 'data') {
  1250. value = elementControllers[require];
  1251. }
  1252. value = value || $element[retrievalMethod]('$' + require + 'Controller');
  1253. if (!value && !optional) {
  1254. throw $compileMinErr('ctreq',
  1255. "Controller '{0}', required by directive '{1}', can't be found!",
  1256. require, directiveName);
  1257. }
  1258. return value;
  1259. } else if (isArray(require)) {
  1260. value = [];
  1261. forEach(require, function(require) {
  1262. value.push(getControllers(require, $element, elementControllers));
  1263. });
  1264. }
  1265. return value;
  1266. }
  1267. function nodeLinkFn(childLinkFn, scope, linkNode, $rootElement, boundTranscludeFn) {
  1268. var attrs, $element, i, ii, linkFn, controller, isolateScope, elementControllers = {}, transcludeFn;
  1269. if (compileNode === linkNode) {
  1270. attrs = templateAttrs;
  1271. } else {
  1272. attrs = shallowCopy(templateAttrs, new Attributes(jqLite(linkNode), templateAttrs.$attr));
  1273. }
  1274. $element = attrs.$$element;
  1275. if (newIsolateScopeDirective) {
  1276. var LOCAL_REGEXP = /^\s*([@=&])(\??)\s*(\w*)\s*$/;
  1277. var $linkNode = jqLite(linkNode);
  1278. isolateScope = scope.$new(true);
  1279. if (templateDirective && (templateDirective === newIsolateScopeDirective.$$originalDirective)) {
  1280. $linkNode.data('$isolateScope', isolateScope) ;
  1281. } else {
  1282. $linkNode.data('$isolateScopeNoTemplate', isolateScope);
  1283. }
  1284. safeAddClass($linkNode, 'ng-isolate-scope');
  1285. forEach(newIsolateScopeDirective.scope, function(definition, scopeName) {
  1286. var match = definition.match(LOCAL_REGEXP) || [],
  1287. attrName = match[3] || scopeName,
  1288. optional = (match[2] == '?'),
  1289. mode = match[1], // @, =, or &
  1290. lastValue,
  1291. parentGet, parentSet, compare;
  1292. isolateScope.$$isolateBindings[scopeName] = mode + attrName;
  1293. switch (mode) {
  1294. case '@':
  1295. attrs.$observe(attrName, function(value) {
  1296. isolateScope[scopeName] = value;
  1297. });
  1298. attrs.$$observers[attrName].$$scope = scope;
  1299. if( attrs[attrName] ) {
  1300. // If the attribute has been provided then we trigger an interpolation to ensure
  1301. // the value is there for use in the link fn
  1302. isolateScope[scopeName] = $interpolate(attrs[attrName])(scope);
  1303. }
  1304. break;
  1305. case '=':
  1306. if (optional && !attrs[attrName]) {
  1307. return;
  1308. }
  1309. parentGet = $parse(attrs[attrName]);
  1310. if (parentGet.literal) {
  1311. compare = equals;
  1312. } else {
  1313. compare = function(a,b) { return a === b; };
  1314. }
  1315. parentSet = parentGet.assign || function() {
  1316. // reset the change, or we will throw this exception on every $digest
  1317. lastValue = isolateScope[scopeName] = parentGet(scope);
  1318. throw $compileMinErr('nonassign',
  1319. "Expression '{0}' used with directive '{1}' is non-assignable!",
  1320. attrs[attrName], newIsolateScopeDirective.name);
  1321. };
  1322. lastValue = isolateScope[scopeName] = parentGet(scope);
  1323. isolateScope.$watch(function parentValueWatch() {
  1324. var parentValue = parentGet(scope);
  1325. if (!compare(parentValue, isolateScope[scopeName])) {
  1326. // we are out of sync and need to copy
  1327. if (!compare(parentValue, lastValue)) {
  1328. // parent changed and it has precedence
  1329. isolateScope[scopeName] = parentValue;
  1330. } else {
  1331. // if the parent can be assigned then do so
  1332. parentSet(scope, parentValue = isolateScope[scopeName]);
  1333. }
  1334. }
  1335. return lastValue = parentValue;
  1336. }, null, parentGet.literal);
  1337. break;
  1338. case '&':
  1339. parentGet = $parse(attrs[attrName]);
  1340. isolateScope[scopeName] = function(locals) {
  1341. return parentGet(scope, locals);
  1342. };
  1343. break;
  1344. default:
  1345. throw $compileMinErr('iscp',
  1346. "Invalid isolate scope definition for directive '{0}'." +
  1347. " Definition: {... {1}: '{2}' ...}",
  1348. newIsolateScopeDirective.name, scopeName, definition);
  1349. }
  1350. });
  1351. }
  1352. transcludeFn = boundTranscludeFn && controllersBoundTransclude;
  1353. if (controllerDirectives) {
  1354. forEach(controllerDirectives, function(directive) {
  1355. var locals = {
  1356. $scope: directive === newIsolateScopeDirective || directive.$$isolateScope ? isolateScope : scope,
  1357. $element: $element,
  1358. $attrs: attrs,
  1359. $transclude: transcludeFn
  1360. }, controllerInstance;
  1361. controller = directive.controller;
  1362. if (controller == '@') {
  1363. controller = attrs[directive.name];
  1364. }
  1365. controllerInstance = $controller(controller, locals);
  1366. // For directives with element transclusion the element is a comment,
  1367. // but jQuery .data doesn't support attaching data to comment nodes as it's hard to
  1368. // clean up (http://bugs.jquery.com/ticket/8335).
  1369. // Instead, we save the controllers for the element in a local hash and attach to .data
  1370. // later, once we have the actual element.
  1371. elementControllers[directive.name] = controllerInstance;
  1372. if (!hasElementTranscludeDirective) {
  1373. $element.data('$' + directive.name + 'Controller', controllerInstance);
  1374. }
  1375. if (directive.controllerAs) {
  1376. locals.$scope[directive.controllerAs] = controllerInstance;
  1377. }
  1378. });
  1379. }
  1380. // PRELINKING
  1381. for(i = 0, ii = preLinkFns.length; i < ii; i++) {
  1382. try {
  1383. linkFn = preLinkFns[i];
  1384. linkFn(linkFn.isolateScope ? isolateScope : scope, $element, attrs,
  1385. linkFn.require && getControllers(linkFn.require, $element, elementControllers), transcludeFn);
  1386. } catch (e) {
  1387. $exceptionHandler(e, startingTag($element));
  1388. }
  1389. }
  1390. // RECURSION
  1391. // We only pass the isolate scope, if the isolate directive has a template,
  1392. // otherwise the child elements do not belong to the isolate directive.
  1393. var scopeToChild = scope;
  1394. if (newIsolateScopeDirective && (newIsolateScopeDirective.template || newIsolateScopeDirective.templateUrl === null)) {
  1395. scopeToChild = isolateScope;
  1396. }
  1397. childLinkFn && childLinkFn(scopeToChild, linkNode.childNodes, undefined, boundTranscludeFn);
  1398. // POSTLINKING
  1399. for(i = postLinkFns.length - 1; i >= 0; i--) {
  1400. try {
  1401. linkFn = postLinkFns[i];
  1402. linkFn(linkFn.isolateScope ? isolateScope : scope, $element, attrs,
  1403. linkFn.require && getControllers(linkFn.require, $element, elementControllers), transcludeFn);
  1404. } catch (e) {
  1405. $exceptionHandler(e, startingTag($element));
  1406. }
  1407. }
  1408. // This is the function that is injected as `$transclude`.
  1409. function controllersBoundTransclude(scope, cloneAttachFn) {
  1410. var transcludeControllers;
  1411. // no scope passed
  1412. if (arguments.length < 2) {
  1413. cloneAttachFn = scope;
  1414. scope = undefined;
  1415. }
  1416. if (hasElementTranscludeDirective) {
  1417. transcludeControllers = elementControllers;
  1418. }
  1419. return boundTranscludeFn(scope, cloneAttachFn, transcludeControllers);
  1420. }
  1421. }
  1422. }
  1423. function markDirectivesAsIsolate(directives) {
  1424. // mark all directives as needing isolate scope.
  1425. for (var j = 0, jj = directives.length; j < jj; j++) {
  1426. directives[j] = inherit(directives[j], {$$isolateScope: true});
  1427. }
  1428. }
  1429. /**
  1430. * looks up the directive and decorates it with exception handling and proper parameters. We
  1431. * call this the boundDirective.
  1432. *
  1433. * @param {string} name name of the directive to look up.
  1434. * @param {string} location The directive must be found in specific format.
  1435. * String containing any of theses characters:
  1436. *
  1437. * * `E`: element name
  1438. * * `A': attribute
  1439. * * `C`: class
  1440. * * `M`: comment
  1441. * @returns true if directive was added.
  1442. */
  1443. function addDirective(tDirectives, name, location, maxPriority, ignoreDirective, startAttrName,
  1444. endAttrName) {
  1445. if (name === ignoreDirective) return null;
  1446. var match = null;
  1447. if (hasDirectives.hasOwnProperty(name)) {
  1448. for(var directive, directives = $injector.get(name + Suffix),
  1449. i = 0, ii = directives.length; i<ii; i++) {
  1450. try {
  1451. directive = directives[i];
  1452. if ( (maxPriority === undefined || maxPriority > directive.priority) &&
  1453. directive.restrict.indexOf(location) != -1) {
  1454. if (startAttrName) {
  1455. directive = inherit(directive, {$$start: startAttrName, $$end: endAttrName});
  1456. }
  1457. tDirectives.push(directive);
  1458. match = directive;
  1459. }
  1460. } catch(e) { $exceptionHandler(e); }
  1461. }
  1462. }
  1463. return match;
  1464. }
  1465. /**
  1466. * When the element is replaced with HTML template then the new attributes
  1467. * on the template need to be merged with the existing attributes in the DOM.
  1468. * The desired effect is to have both of the attributes present.
  1469. *
  1470. * @param {object} dst destination attributes (original DOM)
  1471. * @param {object} src source attributes (from the directive template)
  1472. */
  1473. function mergeTemplateAttributes(dst, src) {
  1474. var srcAttr = src.$attr,
  1475. dstAttr = dst.$attr,
  1476. $element = dst.$$element;
  1477. // reapply the old attributes to the new element
  1478. forEach(dst, function(value, key) {
  1479. if (key.charAt(0) != '$') {
  1480. if (src[key]) {
  1481. value += (key === 'style' ? ';' : ' ') + src[key];
  1482. }
  1483. dst.$set(key, value, true, srcAttr[key]);
  1484. }
  1485. });
  1486. // copy the new attributes on the old attrs object
  1487. forEach(src, function(value, key) {
  1488. if (key == 'class') {
  1489. safeAddClass($element, value);
  1490. dst['class'] = (dst['class'] ? dst['class'] + ' ' : '') + value;
  1491. } else if (key == 'style') {
  1492. $element.attr('style', $element.attr('style') + ';' + value);
  1493. dst['style'] = (dst['style'] ? dst['style'] + ';' : '') + value;
  1494. // `dst` will never contain hasOwnProperty as DOM parser won't let it.
  1495. // You will get an "InvalidCharacterError: DOM Exception 5" error if you
  1496. // have an attribute like "has-own-property" or "data-has-own-property", etc.
  1497. } else if (key.charAt(0) != '$' && !dst.hasOwnProperty(key)) {
  1498. dst[key] = value;
  1499. dstAttr[key] = srcAttr[key];
  1500. }
  1501. });
  1502. }
  1503. function compileTemplateUrl(directives, $compileNode, tAttrs,
  1504. $rootElement, childTranscludeFn, preLinkFns, postLinkFns, previousCompileContext) {
  1505. var linkQueue = [],
  1506. afterTemplateNodeLinkFn,
  1507. afterTemplateChildLinkFn,
  1508. beforeTemplateCompileNode = $compileNode[0],
  1509. origAsyncDirective = directives.shift(),
  1510. // The fact that we have to copy and patch the directive seems wrong!
  1511. derivedSyncDirective = extend({}, origAsyncDirective, {
  1512. templateUrl: null, transclude: null, replace: null, $$originalDirective: origAsyncDirective
  1513. }),
  1514. templateUrl = (isFunction(origAsyncDirective.templateUrl))
  1515. ? origAsyncDirective.templateUrl($compileNode, tAttrs)
  1516. : origAsyncDirective.templateUrl;
  1517. $compileNode.empty();
  1518. $http.get($sce.getTrustedResourceUrl(templateUrl), {cache: $templateCache}).
  1519. success(function(content) {
  1520. var compileNode, tempTemplateAttrs, $template, childBoundTranscludeFn;
  1521. content = denormalizeTemplate(content);
  1522. if (origAsyncDirective.replace) {
  1523. $template = jqLite('<div>' + trim(content) + '</div>').contents();
  1524. compileNode = $template[0];
  1525. if ($template.length != 1 || compileNode.nodeType !== 1) {
  1526. throw $compileMinErr('tplrt',
  1527. "Template for directive '{0}' must have exactly one root element. {1}",
  1528. origAsyncDirective.name, templateUrl);
  1529. }
  1530. tempTemplateAttrs = {$attr: {}};
  1531. replaceWith($rootElement, $compileNode, compileNode);
  1532. var templateDirectives = collectDirectives(compileNode, [], tempTemplateAttrs);
  1533. if (isObject(origAsyncDirective.scope)) {
  1534. markDirectivesAsIsolate(templateDirectives);
  1535. }
  1536. directives = templateDirectives.concat(directives);
  1537. mergeTemplateAttributes(tAttrs, tempTemplateAttrs);
  1538. } else {
  1539. compileNode = beforeTemplateCompileNode;
  1540. $compileNode.html(content);
  1541. }
  1542. directives.unshift(derivedSyncDirective);
  1543. afterTemplateNodeLinkFn = applyDirectivesToNode(directives, compileNode, tAttrs,
  1544. childTranscludeFn, $compileNode, origAsyncDirective, preLinkFns, postLinkFns,
  1545. previousCompileContext);
  1546. forEach($rootElement, function(node, i) {
  1547. if (node == compileNode) {
  1548. $rootElement[i] = $compileNode[0];
  1549. }
  1550. });
  1551. afterTemplateChildLinkFn = compileNodes($compileNode[0].childNodes, childTranscludeFn);
  1552. while(linkQueue.length) {
  1553. var scope = linkQueue.shift(),
  1554. beforeTemplateLinkNode = linkQueue.shift(),
  1555. linkRootElement = linkQueue.shift(),
  1556. boundTranscludeFn = linkQueue.shift(),
  1557. linkNode = $compileNode[0];
  1558. if (beforeTemplateLinkNode !== beforeTemplateCompileNode) {
  1559. // it was cloned therefore we have to clone as well.
  1560. linkNode = jqLiteClone(compileNode);
  1561. replaceWith(linkRootElement, jqLite(beforeTemplateLinkNode), linkNode);
  1562. }
  1563. if (afterTemplateNodeLinkFn.transclude) {
  1564. childBoundTranscludeFn = createBoundTranscludeFn(scope, afterTemplateNodeLinkFn.transclude);
  1565. } else {
  1566. childBoundTranscludeFn = boundTranscludeFn;
  1567. }
  1568. afterTemplateNodeLinkFn(afterTemplateChildLinkFn, scope, linkNode, $rootElement,
  1569. childBoundTranscludeFn);
  1570. }
  1571. linkQueue = null;
  1572. }).
  1573. error(function(response, code, headers, config) {
  1574. throw $compileMinErr('tpload', 'Failed to load template: {0}', config.url);
  1575. });
  1576. return function delayedNodeLinkFn(ignoreChildLinkFn, scope, node, rootElement, boundTranscludeFn) {
  1577. if (linkQueue) {
  1578. linkQueue.push(scope);
  1579. linkQueue.push(node);
  1580. linkQueue.push(rootElement);
  1581. linkQueue.push(boundTranscludeFn);
  1582. } else {
  1583. afterTemplateNodeLinkFn(afterTemplateChildLinkFn, scope, node, rootElement, boundTranscludeFn);
  1584. }
  1585. };
  1586. }
  1587. /**
  1588. * Sorting function for bound directives.
  1589. */
  1590. function byPriority(a, b) {
  1591. var diff = b.priority - a.priority;
  1592. if (diff !== 0) return diff;
  1593. if (a.name !== b.name) return (a.name < b.name) ? -1 : 1;
  1594. return a.index - b.index;
  1595. }
  1596. function assertNoDuplicate(what, previousDirective, directive, element) {
  1597. if (previousDirective) {
  1598. throw $compileMinErr('multidir', 'Multiple directives [{0}, {1}] asking for {2} on: {3}',
  1599. previousDirective.name, directive.name, what, startingTag(element));
  1600. }
  1601. }
  1602. function addTextInterpolateDirective(directives, text) {
  1603. var interpolateFn = $interpolate(text, true);
  1604. if (interpolateFn) {
  1605. directives.push({
  1606. priority: 0,
  1607. compile: valueFn(function textInterpolateLinkFn(scope, node) {
  1608. var parent = node.parent(),
  1609. bindings = parent.data('$binding') || [];
  1610. bindings.push(interpolateFn);
  1611. safeAddClass(parent.data('$binding', bindings), 'ng-binding');
  1612. scope.$watch(interpolateFn, function interpolateFnWatchAction(value) {
  1613. node[0].nodeValue = value;
  1614. });
  1615. })
  1616. });
  1617. }
  1618. }
  1619. function getTrustedContext(node, attrNormalizedName) {
  1620. if (attrNormalizedName == "srcdoc") {
  1621. return $sce.HTML;
  1622. }
  1623. var tag = nodeName_(node);
  1624. // maction[xlink:href] can source SVG. It's not limited to <maction>.
  1625. if (attrNormalizedName == "xlinkHref" ||
  1626. (tag == "FORM" && attrNormalizedName == "action") ||
  1627. (tag != "IMG" && (attrNormalizedName == "src" ||
  1628. attrNormalizedName == "ngSrc"))) {
  1629. return $sce.RESOURCE_URL;
  1630. }
  1631. }
  1632. function addAttrInterpolateDirective(node, directives, value, name) {
  1633. var interpolateFn = $interpolate(value, true);
  1634. // no interpolation found -> ignore
  1635. if (!interpolateFn) return;
  1636. if (name === "multiple" && nodeName_(node) === "SELECT") {
  1637. throw $compileMinErr("selmulti",
  1638. "Binding to the 'multiple' attribute is not supported. Element: {0}",
  1639. startingTag(node));
  1640. }
  1641. directives.push({
  1642. priority: 100,
  1643. compile: function() {
  1644. return {
  1645. pre: function attrInterpolatePreLinkFn(scope, element, attr) {
  1646. var $$observers = (attr.$$observers || (attr.$$observers = {}));
  1647. if (EVENT_HANDLER_ATTR_REGEXP.test(name)) {
  1648. throw $compileMinErr('nodomevents',
  1649. "Interpolations for HTML DOM event attributes are disallowed. Please use the " +
  1650. "ng- versions (such as ng-click instead of onclick) instead.");
  1651. }
  1652. // we need to interpolate again, in case the attribute value has been updated
  1653. // (e.g. by another directive's compile function)
  1654. interpolateFn = $interpolate(attr[name], true, getTrustedContext(node, name));
  1655. // if attribute was updated so that there is no interpolation going on we don't want to
  1656. // register any observers
  1657. if (!interpolateFn) return;
  1658. // TODO(i): this should likely be attr.$set(name, iterpolateFn(scope) so that we reset the
  1659. // actual attr value
  1660. attr[name] = interpolateFn(scope);
  1661. ($$observers[name] || ($$observers[name] = [])).$$inter = true;
  1662. (attr.$$observers && attr.$$observers[name].$$scope || scope).
  1663. $watch(interpolateFn, function interpolateFnWatchAction(newValue, oldValue) {
  1664. //special case for class attribute addition + removal
  1665. //so that class changes can tap into the animation
  1666. //hooks provided by the $animate service. Be sure to
  1667. //skip animations when the first digest occurs (when
  1668. //both the new and the old values are the same) since
  1669. //the CSS classes are the non-interpolated values
  1670. if(name === 'class' && newValue != oldValue) {
  1671. attr.$updateClass(newValue, oldValue);
  1672. } else {
  1673. attr.$set(name, newValue);
  1674. }
  1675. });
  1676. }
  1677. };
  1678. }
  1679. });
  1680. }
  1681. /**
  1682. * This is a special jqLite.replaceWith, which can replace items which
  1683. * have no parents, provided that the containing jqLite collection is provided.
  1684. *
  1685. * @param {JqLite=} $rootElement The root of the compile tree. Used so that we can replace nodes
  1686. * in the root of the tree.
  1687. * @param {JqLite} elementsToRemove The jqLite element which we are going to replace. We keep
  1688. * the shell, but replace its DOM node reference.
  1689. * @param {Node} newNode The new DOM node.
  1690. */
  1691. function replaceWith($rootElement, elementsToRemove, newNode) {
  1692. var firstElementToRemove = elementsToRemove[0],
  1693. removeCount = elementsToRemove.length,
  1694. parent = firstElementToRemove.parentNode,
  1695. i, ii;
  1696. if ($rootElement) {
  1697. for(i = 0, ii = $rootElement.length; i < ii; i++) {
  1698. if ($rootElement[i] == firstElementToRemove) {
  1699. $rootElement[i++] = newNode;
  1700. for (var j = i, j2 = j + removeCount - 1,
  1701. jj = $rootElement.length;
  1702. j < jj; j++, j2++) {
  1703. if (j2 < jj) {
  1704. $rootElement[j] = $rootElement[j2];
  1705. } else {
  1706. delete $rootElement[j];
  1707. }
  1708. }
  1709. $rootElement.length -= removeCount - 1;
  1710. break;
  1711. }
  1712. }
  1713. }
  1714. if (parent) {
  1715. parent.replaceChild(newNode, firstElementToRemove);
  1716. }
  1717. var fragment = document.createDocumentFragment();
  1718. fragment.appendChild(firstElementToRemove);
  1719. newNode[jqLite.expando] = firstElementToRemove[jqLite.expando];
  1720. for (var k = 1, kk = elementsToRemove.length; k < kk; k++) {
  1721. var element = elementsToRemove[k];
  1722. jqLite(element).remove(); // must do this way to clean up expando
  1723. fragment.appendChild(element);
  1724. delete elementsToRemove[k];
  1725. }
  1726. elementsToRemove[0] = newNode;
  1727. elementsToRemove.length = 1;
  1728. }
  1729. function cloneAndAnnotateFn(fn, annotation) {
  1730. return extend(function() { return fn.apply(null, arguments); }, fn, annotation);
  1731. }
  1732. }];
  1733. }
  1734. var PREFIX_REGEXP = /^(x[\:\-_]|data[\:\-_])/i;
  1735. /**
  1736. * Converts all accepted directives format into proper directive name.
  1737. * All of these will become 'myDirective':
  1738. * my:Directive
  1739. * my-directive
  1740. * x-my-directive
  1741. * data-my:directive
  1742. *
  1743. * Also there is special case for Moz prefix starting with upper case letter.
  1744. * @param name Name to normalize
  1745. */
  1746. function directiveNormalize(name) {
  1747. return camelCase(name.replace(PREFIX_REGEXP, ''));
  1748. }
  1749. /**
  1750. * @ngdoc object
  1751. * @name ng.$compile.directive.Attributes
  1752. *
  1753. * @description
  1754. * A shared object between directive compile / linking functions which contains normalized DOM
  1755. * element attributes. The values reflect current binding state `{{ }}`. The normalization is
  1756. * needed since all of these are treated as equivalent in Angular:
  1757. *
  1758. * <span ng:bind="a" ng-bind="a" data-ng-bind="a" x-ng-bind="a">
  1759. */
  1760. /**
  1761. * @ngdoc property
  1762. * @name ng.$compile.directive.Attributes#$attr
  1763. * @propertyOf ng.$compile.directive.Attributes
  1764. * @returns {object} A map of DOM element attribute names to the normalized name. This is
  1765. * needed to do reverse lookup from normalized name back to actual name.
  1766. */
  1767. /**
  1768. * @ngdoc function
  1769. * @name ng.$compile.directive.Attributes#$set
  1770. * @methodOf ng.$compile.directive.Attributes
  1771. * @function
  1772. *
  1773. * @description
  1774. * Set DOM element attribute value.
  1775. *
  1776. *
  1777. * @param {string} name Normalized element attribute name of the property to modify. The name is
  1778. * revers translated using the {@link ng.$compile.directive.Attributes#$attr $attr}
  1779. * property to the original name.
  1780. * @param {string} value Value to set the attribute to. The value can be an interpolated string.
  1781. */
  1782. /**
  1783. * Closure compiler type information
  1784. */
  1785. function nodesetLinkingFn(
  1786. /* angular.Scope */ scope,
  1787. /* NodeList */ nodeList,
  1788. /* Element */ rootElement,
  1789. /* function(Function) */ boundTranscludeFn
  1790. ){}
  1791. function directiveLinkingFn(
  1792. /* nodesetLinkingFn */ nodesetLinkingFn,
  1793. /* angular.Scope */ scope,
  1794. /* Node */ node,
  1795. /* Element */ rootElement,
  1796. /* function(Function) */ boundTranscludeFn
  1797. ){}
  1798. function tokenDifference(str1, str2) {
  1799. var values = '',
  1800. tokens1 = str1.split(/\s+/),
  1801. tokens2 = str2.split(/\s+/);
  1802. outer:
  1803. for(var i = 0; i < tokens1.length; i++) {
  1804. var token = tokens1[i];
  1805. for(var j = 0; j < tokens2.length; j++) {
  1806. if(token == tokens2[j]) continue outer;
  1807. }
  1808. values += (values.length > 0 ? ' ' : '') + token;
  1809. }
  1810. return values;
  1811. }