繁体   English   中英

AngularJS-将click事件绑定到指令元素的子级

[英]AngularJS - Bind click event to children of directive element

我回到使用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();
            });
        }
    };

我想将click事件分配给第一个子div(我在其中检查CSS)并根据“ data-url”执行某些任务,但我真的不想在我的HTML中向该子对象添加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
            }
        });
    })
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM