Bind event to child element of directive in link function

南楼画角 提交于 2019-12-05 16:53:11

I've resolved the same problem with the angular $timeout

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

Try this by injecting $timeout in your directive

Solution #1 using angular ng-click directive (plunker)

<button ng-click="showValuePopup = !showValuePopup;">Click</button>
<div ng-show="showValuePopup">
    <ul>
        <li ng-click="$parent.showValuePopup = false;" ng-repeat="option in options" value="{{ option.value }}"
            symbol="{{ option.symbol }}">{{ option.text }}
        </li>
    </ul>
</div>

Solution #2 use additional directive with timeout that fire event after ng-repeat last element loads (plunker)

app.directive('onLastRepeat', function () {
    return function (scope, element, attrs) {
        if (scope.$last) setTimeout(function () {
            debugger;
            scope.$emit('onRepeatLast', element, attrs);
        }, 1);
    };
});

and listen for this event in link function:

$scope.$on('onRepeatLast', function(scope, element, attrs){
    // make what you want
    valuePopup.find('li').on('click',function(){
        valuePopup.hide();
    });
    valuePopup.find('keydown').on('click',function(){
        valuePopup.hide();
    });
});

maybe it will help you

app.directive('gtmsCycleButton', function () {
    return{
        restrict: 'EA',
        link: function (scope, el, attrs) {

            scope.$watch(attrs.options, function(newVal, oldVal) {

                if (newVal === oldVal) return;

                var btn = $(el).find('.v-btn'),
                    valuePopup = $(el).find('.v-value-popup');

                btn.on('click', function() {
                    console.log('Button Clicked');
                    valuePopup.toggle().focus();
                });

                valuePopup.find('li').on('click', function() {
                    valuePopup.hide();
                });

                valuePopup.find('keydown').on('click', function() {
                    valuePopup.hide();
                });
            });            
        },
        templateUrl: 'temp1'
    }
});
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!