@ngdoc overview @name Directives @description Directives are a way to teach HTML new tricks. During DOM compilation directives are matched against the HTML and executed. This allows directives to register behavior, or transform the DOM. Angular comes with a built in set of directives which are useful for building web applications but can be extended such that HTML can be turned into a declarative domain specific language (DSL). # Invoking directives from HTML Directives have camel cased names such as `ngBind`. The directive can be invoked by translating the camel case name into snake case with these special characters `:`, `-`, or `_`. Optionally the directive can be prefixed with `x-`, or `data-` to make it HTML validator compliant. Here is a list of some of the possible directive names: `ng:bind`, `ng-bind`, `ng_bind`, `x-ng-bind` and `data-ng-bind`. The directives can be placed in element names, attributes, class names, as well as comments. Here are some equivalent examples of invoking `myDir`. (However, most directives are restricted to attribute only.)
Directives can be invoked in many different ways, but are equivalent in the end result as shown in the following example.
Hello {{username}}!# ngAttr attribute bindings If an attribute with a binding is prefixed with `ngAttr` prefix (denormalized prefix: 'ng-attr-', 'ng:attr-') then during the compilation the prefix will be removed and the binding will be applied to an unprefixed attribute. This allows binding to attributes that would otherwise be eagerly processed by browsers in their uncompiled form (e.g. `img[src]` or svg's `circle[cx]` attributes). For example, considering template: and model cx set to 5, will result in rendering this dom: If you were to bind `{{cx}}` directly to the `cx` attribute, you'd get the following error: `Error: Invalid value for attribute cx="{{cx}}"`. With `ng-attr-cx` you can work around this problem. # Compilation process, and directive matching Compilation of HTML happens in three phases: 1. First the HTML is parsed into DOM using the standard browser API. This is important to realize because the templates must be parsable HTML. This is in contrast to most templating systems that operate on strings, rather than on DOM elements. 2. The compilation of the DOM is performed by the call to the {@link api/ng.$compile $compile()} method. The method traverses the DOM and matches the directives. If a match is found it is added to the list of directives associated with the given DOM element. Once all directives for a given DOM element have been identified they are sorted by priority and their `compile()` functions are executed. The directive compile function has a chance to modify the DOM structure and is responsible for producing a `link()` function explained next. The {@link api/ng.$compile $compile()} method returns a combined linking function, which is a collection of all of the linking functions returned from the individual directive compile functions. 3. Link the template with scope by calling the linking function returned from the previous step. This in turn will call the linking function of the individual directives allowing them to register any listeners on the elements and set up any {@link api/ng.$rootScope.Scope#$watch watches} with the {@link api/ng.$rootScope.Scope scope}. The result of this is a live binding between the scope and the DOM. A change in the scope is reflected in the DOM.
var $compile = ...; // injected into your code var scope = ...; var html = ''; // Step 1: parse HTML into DOM element var template = angular.element(html); // Step 2: compile the template var linkFn = $compile(template); // Step 3: link the compiled template with the scope. linkFn(scope);## Reasons behind the compile/link separation At this point you may wonder why the compile process is broken down to a compile and link phase. To understand this, let's look at a real world example with a repeater:
Hello {{user}}, you have these actions:
var myModule = angular.module(...); myModule.directive('directiveName', function factory(injectables) { var directiveDefinitionObject = { priority: 0, template: '', // or // function(tElement, tAttrs) { ... }, // or // templateUrl: 'directive.html', // or // function(tElement, tAttrs) { ... }, replace: false, transclude: false, restrict: 'A', scope: false, controller: function($scope, $element, $attrs, $transclude, otherInjectables) { ... }, require: 'siblingDirectiveName', // or // ['^parentDirectiveName', '?optionalDirectiveName', '?^optionalParent'], compile: function compile(tElement, tAttrs, transclude) { return { pre: function preLink(scope, iElement, iAttrs, controller) { ... }, post: function postLink(scope, iElement, iAttrs, controller) { ... } } // or // return function postLink( ... ) { ... } }, // or // link: { // pre: function preLink(scope, iElement, iAttrs, controller) { ... }, // post: function postLink(scope, iElement, iAttrs, controller) { ... } // } // or // link: function postLink( ... ) { ... } }; return directiveDefinitionObject; });In most cases you will not need such fine control and so the above can be simplified. You can still return a Directive Definition Object, but only setting the 'link' function property of the Object, and rely on the default values for other properties. Therefore the above can be simplified as:
var myModule = angular.module(...); myModule.directive('directiveName', function factory(injectables) { var directiveDefinitionObject = { link: function postLink(scope, iElement, iAttrs) { ... } }; return directiveDefinitionObject; // or // return function postLink(scope, iElement, iAttrs) { ... } });## Factory method The factory method is responsible for creating the directive. It is invoked only once, when the {@link api/ng.$compile compiler} matches the directive for the first time. You can perform any initialization work here. The method is invoked using the {@link api/AUTO.$injector#invoke $injector.invoke} which makes it injectable following all of the rules of injection annotation. ## Directive Definition Object The directive definition object provides instructions to the {@link api/ng.$compile compiler}. The attributes are: * `name` - Name of the current scope. Optional and defaults to the name at registration. * `priority` - When there are multiple directives defined on a single DOM element, sometimes it is necessary to specify the order in which the directives are applied. The `priority` is used to sort the directives before their `compile` functions get called. Priority is defined as a number. Directives with greater numerical `priority` are compiled first. The order of directives with the same priority is undefined. The default priority is `0`. * `terminal` - If set to true then the current `priority` will be the last set of directives which will execute (any directives at the current priority will still execute as the order of execution on same `priority` is undefined). * `scope` - If set to: * `true` - then a new scope will be created for this directive. If multiple directives on the same element request a new scope, only one new scope is created. The new scope rule does not apply for the root of the template since the root of the template always gets a new scope. * `{}` (object hash) - then a new 'isolate' scope is created. The 'isolate' scope differs from normal scope in that it does not prototypically inherit from the parent scope. This is useful when creating reusable components, which should not accidentally read or modify data in the parent scope.
function compile(tElement, tAttrs, transclude) { ... }The compile function deals with transforming the template DOM. Since most directives do not do template transformation, it is not used often. Examples that require compile functions are directives that transform template DOM, such as {@link api/ng.directive:ngRepeat ngRepeat}, or load the contents asynchronously, such as {@link api/ngRoute.directive:ngView ngView}. The compile function takes the following arguments. * `tElement` - template element - The element where the directive has been declared. It is safe to do template transformation on the element and child elements only. * `tAttrs` - template attributes - Normalized list of attributes declared on this element shared between all directive compile functions. See {@link guide/directive#Attributes Attributes}. * `transclude` - A transclude linking function: `function(scope, cloneLinkingFn)`. NOTE: The template instance and the link instance may not be the same objects if the template has been cloned. For this reason it is not safe in the compile function to do anything other than DOM transformation that applies to all DOM clones. Specifically, DOM listener registration should be done in a linking function rather than in a compile function. A compile function can have a return value which can be either a function or an object. * returning a (post-link) function - is equivalent to registering the linking function via the `link` property of the config object when the compile function is empty. * returning an object with function(s) registered via `pre` and `post` properties - allows you to control when a linking function should be called during the linking phase. See info about pre-linking and post-linking functions below. ## Linking function
function link(scope, iElement, iAttrs, controller) { ... }The link function is responsible for registering DOM listeners as well as updating the DOM. It is executed after the template has been cloned. This is where most of the directive logic will be put. * `scope` - {@link api/ng.$rootScope.Scope Scope} - The scope to be used by the directive for registering {@link api/ng.$rootScope.Scope#$watch watches}. * `iElement` - instance element - The element where the directive is to be used. It is safe to manipulate the children of the element only in `postLink` function since the children have already been linked. * `iAttrs` - instance attributes - Normalized list of attributes declared on this element shared between all directive linking functions. See {@link guide/directive#Attributes Attributes}. * `controller` - a controller instance - A controller instance if at least one directive on the element defines a controller. The controller is shared among all the directives, which allows the directives to use the controllers as a communication channel. ### Pre-linking function Executed before the child elements are linked. Not safe to do DOM transformation since the compiler linking function will fail to locate the correct elements for linking. ### Post-linking function Executed after the child elements are linked. It is safe to do DOM transformation in the post-linking function. ## Attributes The {@link api/ng.$compile.directive.Attributes Attributes} object - passed as a parameter in the link() or compile() functions - is a way of accessing: * *normalized attribute names:* Since a directive such as 'ngBind' can be expressed in many ways such as 'ng:bind', or 'x-ng-bind', the attributes object allows for normalized access to the attributes. * *directive inter-communication:* All directives share the same instance of the attributes object which allows the directives to use the attributes object as inter directive communication. * *supports interpolation:* Interpolation attributes are assigned to the attribute object allowing other directives to read the interpolated value. * *observing interpolated attributes:* Use `$observe` to observe the value changes of attributes that contain interpolation (e.g. `src="{{bar}}"`). Not only is this very efficient but it's also the only way to easily get the actual value because during the linking phase the interpolation hasn't been evaluated yet and so the value is at this time set to `undefined`.
function linkingFn(scope, elm, attrs, ctrl) { // get the attribute value console.log(attrs.ngModel); // change the attribute attrs.$set('ngModel', 'new value'); // observe changes to interpolated attribute attrs.$observe('ngModel', function(value) { console.log('ngModel has changed value to ' + value); }); }# Understanding Transclusion and Scopes It is often desirable to have reusable components. Below is a pseudo code showing how a simplified dialog component may work.
Clicking on the "show" button will open the dialog. The dialog will have a title, which is data bound to `username`, and it will also have a body which we would like to transclude into the dialog. Here is an example of what the template definition for the `dialog` widget may look like.
This will not render properly, unless we do some scope magic. The first issue we have to solve is that the dialog box template expects `title` to be defined, but the place of instantiation would like to bind to `username`. Furthermore the buttons expect the `onOk` and `onCancel` functions to be present in the scope. This limits the usefulness of the widget. To solve the mapping issue we use the `locals` to create local variables which the template expects as follows:{{title}}
scope: { title: '@', // the title uses the data-binding from the parent scope onOk: '&', // create a delegate onOk function onCancel: '&', // create a delegate onCancel function visible: '=' // set up visible to accept data-binding }Creating local properties on widget scope creates two problems: 1. isolation - if the user forgets to set `title` attribute of the dialog widget the dialog template will bind to parent scope property. This is unpredictable and undesirable. 2. transclusion - the transcluded DOM can see the widget locals, which may overwrite the properties which the transclusion needs for data-binding. In our example the `title` property of the widget clobbers the `title` property of the transclusion. To solve the issue of lack of isolation, the directive declares a new `isolated` scope. An isolated scope does not prototypically inherit from the child scope, and therefore we don't have to worry about accidentally clobbering any properties. However `isolated` scope creates a new problem: if a transcluded DOM is a child of the widget isolated scope then it will not be able to bind to anything. For this reason the transcluded scope is a child of the original scope, before the widget created an isolated scope for its local variables. This makes the transcluded and widget isolated scope siblings. This may seem to be unexpected complexity, but it gives the widget user and developer the least surprise. Therefore the final directive definition looks something like this:
transclude: true, scope: { title: '@', // the title uses the data-binding from the parent scope onOk: '&', // create a delegate onOk function onCancel: '&', // create a delegate onCancel function visible: '=' // set up visible to accept data-binding }, restrict: 'E', replace: true# Creating Components It is often desirable to replace a single directive with a more complex DOM structure. This allows the directives to become a short hand for reusable components from which applications can be built. Following is an example of building a reusable widget.