Bind an event to a child of a directive in a communication function

It is necessary to associate an event with a directive for children, which is prepared using ng-repeat in templateUrl. I am trying to relate an event to a function link, but the children are not yet prepared.

Here is the plunker.

Here I want to bind an event clickto a tag liprepared with ng-repeat. But at the time of execution, the linkelements lihave not yet been prepared. enter image description here

Can someone help.

+4
source share
3 answers

I solved the same problem with angular $ timeout

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

Try this by entering $ timeout in your directive

+4

β„– 1 angular ng-click (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>

β„–2 , ng-repeat (plunker)

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

:

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

maybe this 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'
    }
});
0
source

Source: https://habr.com/ru/post/1569041/


All Articles