假设我有 A 和 B 可重用组件。我希望 B 调用 A 上的方法 - 当然仅当 B 是 A 的子级时。此外 - 我希望 B 用作独立组件(没有 A 作为父级)。在这种情况下,不应调用不存在的 A 中的方法。我的第一次尝试是在链接函数中获取 Controller (与我在 B 上指定 require: "^A"
完全相同的方式 - 现在我不能拥有它,因为我也想将 B 用作一个独立的组件) - 但这不起作用:
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>'
};
});
对于用例:
<A><B></B></A><B></B>
控制台输出应该是:
Hooray!
Standalone
有什么想法吗?谢谢!
最佳答案
您可以有条件地要求另一个指令,并在其前面加上问号:require: "^?A"
。然后,您可以测试 Controller 是否为非空,以查看您是在父指令内调用还是作为独立指令调用。
关于AngularJS:重用具有不同父级的组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14538839/