嵌套 AngularJS 指令中的查询选择器

Query selector in nested AngularJS Directives

我在此 HTML 代码中使用了两个指令:

<div animations>
   <h2>Title</h2>
   <span class="animateBtn">Animate!</span>

   <info-section></info-section>
</div>

第一个是属性指令:

angular.module('app').directive('animations', ['$window', ($window: any) => {
    return {
       restrict: "A",
       link: function ($scope: any, element: any, attrs: any) {
        angular.element(document).ready(() => {
            let animateBtns = angular.element(element[0].querySelector('.animateBtn'));
            if (animateBtns && animateBtns.length) {
                for (let i = 0, animateBtnsLength = animateBtns.length; i < animateBtnsLength; i++) {
                    let currentBtn = animateBtns[i];
                    currentBtn.addEventListener("click", function () {
                        .... other code....
                    });
                }
            }

              ..... other code .....

        });
       }
   };
}])

因此,它只是对 select 所有按钮执行 querySelector,单击这些按钮必须启动特定功能。 它有效。问题是第二个指令 还包含一个 "animateBtn":

.directive('infoSection', function() {
   return {
       replace: true,
       restrict: 'E',
       template: '<div><span class="animateBtn">Animate with this too</span></div>'
   }
});

问题是在第一个指令中(即使我使用 (document).ready()),select 或 returns 只是一个元素(标题下的跨度),并且它不包括第二个指令的 "animateBtn"。

在这里你可以找到完整的代码:PLNKR

与 AngularJS 一起使用指令将代码附加到元素而不是查询选择器:

app.directive("animateBtn", function($window) {
    return {
        restrict: 'C',
        link: postLink
    };
    function postLink (scope, elem, attrs) {
        elem.on('click', function() {

             .... other code....

        });

          .... other code....

    }
})

当 AngularJS 将元素添加到 DOM 时,上述指令会将点击处理程序和关联代码附加到具有 class animateBtn 的每个元素框架。


if a write a function inside "animations" directive, how can I trigger it inside "animatBtn" directive? I mean, in your code, inside the first line of "..... other code...." how can I call a function written in the "animations" directive?

使用DDO的require属性访问animations指令的控制器:

app.directive("animateBtn", function($window) {
    return {
        restrict: 'C',
        link: postLink,
        require: '^animations'
    };
    function postLink (scope, elem, attrs, animations) {
        elem.on('click', function() {

             .... other code....

        });

        //call animations API

        animations.someMethod(args);

    }
})

animations 指令中:

app.directive("animations", function() {
    return {
        controller: ctrl
    }
    function ctrl($element, $scope) {
        this.someMethod = function(args) {
            //code here
        };
    }
})

有关详细信息,请参阅 AngularJS Comprehensive Directive API Reference - require