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

ngModel
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
NgModelController
, I need to write
ngModel
. 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
AbcXyzController
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();
    }
  }
});
<html>

<head>
  <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.6/angular.min.js"></script>
</head>

<body>
  <div ng-app="myFunnyApp">
    <my-funny-directive></my-funny-directive>
  </div>
</body>

</html>