'Bind event to child element of directive in link function

I need to bind an event to directive's children which is prepared with ng-repeat in templateUrl. I am trying to bind the event in link function but the children are not yet prepared.

Here is the plunker.

Here I want to bind click event on li tag which are prepared with ng-repeat.But by the time, the link is executed, the li elements are not yet prepared.

enter image description here



Solution 1:[1]

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();
    });
});

Solution 2:[2]

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'
    }
});

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 finico