maaartinus maaartinus - 9 months ago 36
AngularJS Question

Directive linking to enclosing directive controller with 'require'

I'm trying to get an enclosing controller in an angularjs directive. I also need an

and this should work like

.directive("myFunnyDirective", function(....) {
return {
require: ["ngModel", "?^myFunnyCtrl"],
scope: {},

but my controller does not get found. I'm rather sure that it's because of me having violated the naming convention as when looking for
, I need to write
. So I renamed it and there's still something wrong. As it's some hard to debug magic, I'd like to know, if the rule is really that
require: "?^abcXyz"
looks for an enclosing
or how does it work? Or is an isolated scope in between a problem?

Answer Source

You have to require the enclosing directive (which basically gives you the controller of this directive).

var myFunnyApp = angular.module('myFunnyApp', []);

myFunnyApp.directive("myFunnyDirective", function() {
  return {
    template: '<my-funnier-directive></my-funnier-directive>',
    controller: function() {
      this.getJoke = function() {
        return 'Knock, knock. ...'

myFunnyApp.directive("myFunnierDirective", function() {
  return {
    require: '?^myFunnyDirective',
    scope: {},
    template: 'Tell a joke! - {{joke}}',
    link: function(scope, element, attrs, myFunnyDirectiveCtrl) {
      scope.joke = myFunnyDirectiveCtrl.getJoke();

  <script src=""></script>

  <div ng-app="myFunnyApp">