How to access parent directive's controller by requiring it recursively?

maX picture maX · Oct 13, 2013 · Viewed 23.7k times · Source

I'm trying to reach the controller of a parent "box" directive recursively:

<body ng-app="main">

<!-- no nesting: parent is the just body -->
<box></box>

<script type="text/javascript">
angular.module('main', [])
.directive('box', function() {
    return {
        restrict: 'E',
        controller: function() { },
        require: '?^box',  // find optional PARENT "box" directive
        link: function(scope, iElement, iAttrs, controller) {
            // controller should be undefined, as there is no parent box
            alert('Controller found: ' + (controller !== undefined));
        }
    };
});
</script>
</body>

I'd expect controller variable to be undefined in the link function, but I get the controller of the actual box directive.

So my question is ... how to gain access to the PARENT controller in case like this:

<box>
    <box></box>
</box>

http://jsfiddle.net/gjv9g/1/

Answer

Joel Kornbluh picture Joel Kornbluh · Feb 16, 2015

Since Angular 1.3 you can use two accents ^^ to search for a directive in parent elements "only".

Quote from the Angular Docs on require:

  • (no prefix) - Locate the required controller on the current element. Throw an error if not found.
  • ? - Attempt to locate the required controller or pass null to the link fn if not found.
  • ^ - Locate the required controller by searching the element and its parents. Throw an error if not found.
  • ^^ - Locate the required controller by searching the element's parents. Throw an error if not found.
  • ?^ - Attempt to locate the required controller by searching the element and its parents or pass null to the link fn if not found.
  • ?^^ - Attempt to locate the required controller by searching the element's parents, or pass null to the link fn if not found.

In your case, replace require: '?^box', with require: '?^^box',