Mantisimo
Mantisimo

Reputation: 4283

Angular directive require on the same element

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!

Upvotes: 2

Views: 647

Answers (1)

Deblaton Jean-Philippe
Deblaton Jean-Philippe

Reputation: 11388

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(){}
   }
});

Upvotes: 2

Related Questions