簡體   English   中英

如何從子指令的鏈接函數調用父指令的鏈接函數

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

我有兩個帶有link功能的指令,A directiveA和B directiveB 如何從directiveB調用屬於directiveA A的函數?

到目前為止,我設置代碼的方式是:

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();
            }
        }
    }
});

directiveA.html

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

directiveB.html

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

但是,當我單擊按鈕時,出現一個錯誤,提示TypeError: scope.onLogInButtonClicked is not a function at Scope.link.scope.showAlert

如何簡單地從child指令定義並調用相同的函數?

您需要使用指令的require選項,您可以在其中提及另一個指令在同一元素上,或者它可能是我的父母在指令API的require屬性中使用^ 當您使用require: ^parentDirective將使您能夠訪問需要鏈接功能的childDirective中的parentDirective控制器。

另外,您需要更正模板html,模板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.
            }
        }
    }
});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM