2

Hi trying to require on the same element. According to angular docs this is possible.

A ^ prefix would make the directive look for the controller on its own element or its parents; without any prefix, the directive would look on its own element only.

Following the explanation. I have two directives, myD and myC... want to be able to access myD from myC's link ctrl attribute.

I've included a link to my codepen example.

var app = angular.module("app",[]);


app.directive("myD", function() {
   return {
      restrict : "E",
      template : "<b>myd</d>"
   }
});

app.directive("myC", function() {
   return {
      require : "myD",
      restrict : "A",
      link : function (scope, attr, ele, ctrl) {
         alert(JSON.stringify(ctrl));
      }
   }

});

<div ng-app="app">
   <my-d my-c></my-d>
</div>

http://codepen.io/mantisimo/pen/KWOxeg

Getting the following error:

Error: [$compile:ctreq] Controller 'myD', required by directive 'myC', can't be found!

2
  • 1
    put controller: function(){} inside directive myD? Commented Apr 10, 2017 at 15:11
  • Thanks for that....literally just figured it! :-) Commented Apr 10, 2017 at 15:16

1 Answer 1

2

When you use require, you ask angular to inject the controller of the required element. In your case, the controller was undefined.

The error was in myD where you need to declare a controller.

app.directive("myD", function() {
   return {
      restrict : "E",
      template : "<b>myd</d>",
      controller: function(){}
   }
});
Sign up to request clarification or add additional context in comments.

5 Comments

Just figured it two seconds ago...It's funny how when you define the problem you see the problem... Thanks for the fast response.
Hopefully will save someone else some pain :)
@Mantisimo next time, use a plastic duck ;-)
@Mantisimo if you use components instead of controllers, there is a default controller declared in each docs.angularjs.org/guide/…
And it's recomended to use components if you don't use the link nor the compile functions

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.