如何从子指令的链接函数中调用父指令的链接函数

How to call a parent directive link function from a child directive's link function

本文关键字:链接 函数 指令 调用      更新时间:2023-09-26

我有两个指令,directiveAdirectiveB都具有link函数。如何从directiveB调用属于directiveA的函数?

到目前为止,我的代码设置方式是:

angular.module('myApp').directive('directiveA', function () {
    return {
        templateUrl: 'directiveA.html',
        link: function (scope) {
            scope.directiveAAlert = function () {
                alert('This is A');
            }
        }
    }
});
angular.module('myApp').directive('directiveB', function () {
    return {
        scope: {
            onButtonClicked: '='
        }
        templateUrl: 'directiveB.html',
        link: function (scope) {
            scope.showAlert = function () {
                scope.onButtonClicked();
            }
        }
    }
});

In directiveA.html:

<directive-b onButtonClicked='directiveAAlert'></directive-b>

In directiveB.html:

<button ng-click='showAlert()'></button>

但是当我点击按钮时,我得到一个错误说TypeError: scope.onLogInButtonClicked is not a function at Scope.link.scope.showAlert

如何从子指令简单地定义和调用相同的函数?

你需要使用指令的require选项,在那里你可以提到其他指令将在同一元素上,或者它可能是我的父母在指令API的require属性内使用^。当你使用require: ^parentDirective,这将给你访问parentDirective控制器在链接函数childDirective谁需要它。

另外,你需要纠正你的模板html应该有属性作为-分开替换它的cammelcase。

directiveA.html:

<directive-b on-button-clicked='directiveAAlert()'></directive-b>

directiveB.html

<button ng-click='showAlert()'></button>

angular.module('myApp').directive('directiveA', function () {
    return {
        templateUrl: 'directiveA.html',
        link: function (scope) {
            //code here
        },
        controller: function($scope){
           scope.directiveAAlert = function () {
                alert('This is A');
            }
        }
    }
});
angular.module('myApp').directive('directiveB', function () {
    return {
        scope: {
            onButtonClicked: '='
        },
        require: '^directiveA',
        templateUrl: 'directiveB.html',
        link: function (scope,element,attrs, ctrl) {
            scope.showAlert = function () {
                ctrl.onButtonClicked(); //ctrl has access to the directive a controller.
            }
        }
    }
});