Directives can access the DOM in order to interact with its elements. It can be done by the function called link in our directive. The link function is invoked after the framework is compiled, and it is recommended that you add behavior to the directive. It takes five arguments as follows:
Property | Description |
---|
scope | This is the scope object of the directive |
element | This is the element instance of directive |
attrs | This is the list of attributes declared within the directive's element |
ctrl | This is the controller of the require directive, and it will be available only if it is used with the require property |
transcludeFn | This is the transclude function |
The following code shows the accordion directive using the link function:
index.html
snippet
<accordion-item title="MMM-8790">
White - 10/10/2002 10:00
</accordion-item>
<accordion-item title="ABC-9954">
Black - 10/10/2002 10:36
</accordion-item>
<accordion-item title="XYZ-9768">
Blue - 10/10/2002 11:10
</accordion-item>
directives.html
snippet
parking.directive("accordionItem", function() {
return {
templateUrl: "accordionItem.html",
restrict: "E",
scope: {
title: "@"
},
transclude: true,
link: function(scope, element, attrs, ctrl, transcludeFn) {
element.bind("click", function() {
scope.$apply(function() {
scope.active = !scope.active;
});
});
}
};
});
accordionItem.html
<div class='accordion-item'>
{{title}}
</div>
<div ng-show='active' class='accordion-description' ng-transclude>
</div>