I try to "require" a parent controller (not directive) but AngularJS returns an exception. The code is like this:
app.controller("myController", function ($scole) {
...
});
app.directive("myDirective", function ($q) {
return {
require: "^myController",
template: "",
link: function (scope, element, attrs, myCtrl) {
...
}
};
});
<div ng-controller="myController as myCtrl">
...
<div my-directive>...</div>
...
</div>
Error: [$compile:ctreq] Controller 'myController', required by directive 'myDirective', can't be found!
Why?
Maybe, require
property must be reference to a controller of directive?
Thanks
This is not very conventional what you are trying to do, but if you really want to require outer controller in your directive you can require ngController: app.directive ("myDirective", function ($q) { return { require: "^ngController", template: "", link: function (scope, element, attrs, myCtrl) { // ... console.log (myCtrl); } }; });
You are correct that the require property is for referencing the controllers of other directives. I had suspected, but could not find anything in the official documentation to give me this certainty. Thanks Alex. Require is of using other directives controllers in another directive , please refer the below example
For example, if you needed your directive to work with the ngModel directive then you'd use this feature to require ngModel 's controller so you can call stuff on it like a little API. If you need to share data between directives and controllers, look into services and the various isolate scope binding syntaxes.
Communication between Directives can be done in various ways. When dealing with Directives that have a hierarchical relationship we can use Directive Controllers to talk between them.
Notation require: "^myController"
means that your directive will try to access another directive called myController
and defined on some of the ancestor tags as my-controller
attribute or <my-controller>
tag. In your case you don't have such directive, hence the exception.
This is not very conventional what you are trying to do, but if you really want to require outer controller in your directive you can require ngController
:
app.directive("myDirective", function($q) {
return {
require: "^ngController",
template: "",
link: function(scope, element, attrs, myCtrl) {
// ...
console.log(myCtrl);
}
};
});
However, this is not very good idea. I can't imagine why you might need it like this. I would recommend to look into scope
configuration properties and how you can pass executable function references into your directive from outer controller.
<div my-directive some-callback="test()"></div>
and in directive define scope:
scope: {
someCallback: '&'
}
where in controller you would have $scope.test = function() {};
. Then you would not need to require controller explicitly in directive.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With