require

The require property is used to inject another directive controller as the fourth parameter of the link function. Using this property, we are able to communicate with the other directives. Some of the parameters are shown in the following table:

Prefix Details(noprefix)
This parameter locates the controller inside the current element. It throws an error if the controller is not defined within the require directive.

PrefixDescription
?This parameter tries to locate the controller, passing null to the controller parameter of the link function if not found.
^This parameter locates the controller in the parent element. It throws an error if the controller is not defined within any parent element.
?^This parameter tries to locate the controller in the parent element, passing null to the controller parameter of the link function if not found.

In our last example, each accordion is independent. We can open and close all of them at our will. This property might be used to create an algorithm that closes all the other accordions as soon as we click on each of them:

index.html
snippet
<accordion>
<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>
</accordion>
directives.html
snippet
parking.directive("accordion", function() {
return {
template: "<div ng-transclude></div>",
restrict: "E",
transclude: true
};
});
snippet
parking.directive("accordionItem", function() {
return {
templateUrl: "accordionItem.html",
restrict: "E",
scope: {
title: "@"
},
transclude: true,
require: "^accordion",
link: function(scope, element, attrs, ctrl, transcludeFn) {
element.bind("click", function() {
scope.$apply(function() {
scope.active = !scope.active;
});
});
}
};
});
Now, we need to define the controller inside the accordion directive; otherwise, an error will be thrown that says the controller can't be found.
Related Tutorial
Follow Us
https://www.facebook.com/Rookie-Nerd-638990322793530 https://twitter.com/RookieNerdTutor https://plus.google.com/b/117136517396468545840 #
Contents +