簡體   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