2

Let's say I have A and B reusable components. I want B to invoke a method on A - of course only if B is a child of A. Also - I want B to be used as a standalone component (without A as a parent). In such case the method from non-existing A shouldn't be invoked. My first try was to get controller in link function (exactly in the same way as if I had require: "^A" specified on B - now I cannot have it because I want to use B also as a standalone component) - but this doesn't work:

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

// <A>
module.directive("A", function() {
    return {
        restrict: "E",
        transclude: true,
        replace: true,
        scope: {},
        controller: function($scope, $element, $attrs) {
            this.register = function() {
               console.log("Hooray!");
            };
        },
        template:
            '<div class="ng-a" ng-transclude></div>'
    };
});

// <B>
module.directive("B", function() {
    return {
        restrict: "E",
        transclude: true,
        replace: true,
        scope: {},
        link: function($scope, $element, $attrs, refA) {
            if (refA !== undefined) {
                refA.register();
            } else {
                console.log("Standalone");
            }
        },
        controller: function($scope, $element, $attrs) {
            // Do something.
        },
        template:
            '<div class="ng-b" ng-transclude></div>'
    };
});

For use case:

<A><B></B></A><B></B>

console output should be:

Hooray!
Standalone

Any ideas? Thanks!

1 Answer 1

5

You can conditionally require another directive prefixing it with the question mark: require: "^?A". Then you can test for the controller being not-null to see if you were invoked inside a parent directive or as a standalone.

Sign up to request clarification or add additional context in comments.

2 Comments

is this documented anywhere?
I'll just leave this here for anyone looking for documentation on require prefixes, like I was.

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.