Bind event to child element of directive in link function

12,301

Solution 1

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 2

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();
    });
});
Share:
12,301
Rama Rao M
Author by

Rama Rao M

Updated on June 14, 2022

Comments

  • Rama Rao M
    Rama Rao M almost 2 years

    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

    Can somebody please help.

  • Rama Rao M
    Rama Rao M over 9 years
    Since,I couldn't find any other solution, I was tend to follow your solution.But I would like to wait for some more time for any alternative solution,so I m not going to mark it as accepted answer. I will mark it as accepted,if I won't find any other solution.
  • Milad
    Milad almost 9 years
    "Error: [jqLite:onargs] jqLite#on() does not support the selector or eventData parameters
  • 300hp
    300hp over 8 years
    Should note that this only works if you include jQuery. Otherwise Angular uses jqLite which doesn't support the selector parameter.