Reputation: 23
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!
Upvotes: 2
Views: 1152
Reputation: 117370
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.
Upvotes: 5