When the AngularJS HTML compiler encounters a directive, it runs the directive’s compile function, which returns the link()
function. The link()
function is added to the list of AngularJS directives. Once all directives have been compiled, the HTML compiler calls the link()
functions in order, based on priority.
If you want to modify the DOM inside a custom directive, you should use a link()
function. The link()
function accepts the scope, element, and attributes associated with the directive, allowing you to manipulate the DOM directly within the directive.
Inside the link()
function, you handle the $destroy
event on the directive element and clean up anything necessary. The link()
function is also responsible for registering DOM listeners to handle browser events.
The link()
function uses the following syntax:
link: function(scope, element, attributes, [controller])
The scope
parameter is the scope of the directive, element
is the element where the directive will be inserted, attributes
lists the attributes declared on the element, and controller
is the controller specified by the require
option.
The following directive shows the implementation of a basic link()
function that sets a scope variable, appends data to the DOM element, implements a $destroy
event handler, and adds a $watch
to the scope:
directive('myDirective', function() {
return {
scope: {title: '='},
require: '^otherDirective',
link: function (scope, elem, attr, otherController){
scope.title = "new";
elem.append("Linked");
elem.on('$destroy', function() {
//cleanup code
});
scope.$watch('title', function(newVal){
//watch code
});
}
};