AngularJS:重用具有不同父级的组件

标签 angularjs

假设我有 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/

相关文章:

android - 在 Ionic 应用程序中禁用硬件后退按钮?

javascript - AngularJS 不解析对象数组

javascript - 如何在 Angular 中仅获取/检查表的可见行

javascript - 如何动态更改 css 值(如整个应用程序中的颜色)等

javascript - angularjs FileReader 返回未定义

AngularJS app.run() 文档?

javascript - 如何使用 javascript 更改标签

javascript - 通过状态在页面加载上加载模板 - AngularJS

javascript - 在我的例子中,如何获取 Select 元素中的选定值?

javascript - 下划线,清除对象的所有值但保留键