AngularJS-将点击事件绑定到指令元素的子元素

AngularJS - Bind click event to children of directive element

本文关键字:元素 指令 绑定 事件 AngularJS-      更新时间:2024-06-09

我又开始使用AngularJS了,但我已经忘记了一切。我的html视图中有一个div,它包含一个自定义指令,子div有一个ng-repeat指令,这是我的html:

<div class="row" data-custom-directive>
<div class="col-xs-2 main-nav-cell" data-ng-repeat="nav in mainNavigation.topNavi" data-url="{{ nav.link }}">
    <div> {{ nav.name }} </div>
    <div class="item-counter" data-ng-show="nav.value > 0"> {{ nav.value }} </div>
</div>
</div>

现在,在我的自定义指令中,我等待ng-repeat完成,然后循环子DIV并执行某些任务(此处省略了一些任务)。

.directive('customDirective', function ($location, $timeout, $rootScope) {
    'use strict';
    return{
        restrict: 'A',
        link: function (scope, element) {
            $timeout(function () {
                var i,
                    list = angular.element(element),
                    cssCheck = function () {

                        for (i = 0; i < list[0].children.length; i++) {
                            /* 
                            Here I wish to set a click event on the Child DIV 
                            I have tried list.children()[i].click = fn & list.children()[i].bind('click' fn)
                            but nothing works!
                            */
                            // if the class is there remove it...
                            if (list.children()[i].classList.contains('is-active')) {
                                list.children()[i].classList.remove('is-active');
                            }

                            // if there is a match add the class...
                            if ($location.url().indexOf(list[0].children[i].getAttribute('data-url')) > 0) {
                                console.log('match');
                                list.children()[i].classList.add('is-active');
                            }
                        }
                    };
                $rootScope.$on('$routeChangeSuccess', function () {
                    cssCheck();
                });
                // original kickoff
                cssCheck();
            });
        }
    };

我想给第一个子div分配一个点击事件(在这里我检查CSS),并根据"数据url"执行某些任务。我真的不想在HTML中给子div添加ng-click指令。有人能告诉我如何在子div中添加点击事件吗?

非常感谢

如果使用jQuery:

link: function (scope, element) {
    $timeout(function () {
        element.on('click', ':first', function () {
            console.log('inside event handler of the first child)
        })
    })
}

如果不使用jQuery

link: function (scope, element) {
    $timeout(function () {
        angular.element(element).on('click', function (evt) {
            var isFirstChild = (evt.target.parentElement.children[0] === evt.target);
            if (isFirstChild) {
                // do the stuff
            }
        });
    })
}