As with many other features of AngularJS, you can extend directive functionality by creating your own custom directives. Custom directives allow you to extend the functionality of HTML by implementing the behavior of elements yourself. If you have code that needs to manipulate the DOM, you should make this happen by using a custom directive.
You implement custom directives by calling the directive()
method on a Module
object. The directive()
method accepts the name of a directive as the first parameter and a provider function that returns an object containing the necessary instructions to build the directive object. For example, the following is a basic definition for a directive:
angular.module('myApp', []).
directive('myDirective', function() {
return {
template: 'Name: {{name}} Score: {{score}}'
};
});
The following is a list of the properties you can apply to the object returned by the directive definition as template
is returned in the code above:
template: Allows you to define the AngularJS template text that is inserted into the directive’s element.
templateUrl: Same as template
except that you specify a URL at the server, and the partial template is downloaded and inserted into the directive’s element.
restrict: Allows you to specify whether the directive applies to an HTML element, an attribute, or both.
replace: Tells the compiler to replace the element the directive is defined in with the directive’s template.
transclude: Allows you to specify whether the directive has access to scopes outside the internal scope.
scope: Allows you to specify an internal scope for the directive.
link: Allows you to specify a link function that has access to the scope, DOM element, and other attributes and is able to manipulate the DOM.
controller: Allows you to define a controller within the directive to manage the directive scope and view.
require: Allows you to specify other directives that are required to implement this directive. Providers for those directives must be available for an instance of this directive to be created.
The following sections discuss the directive options in more detail.