Angular ng-click event delegation

后端 未结 4 1520
猫巷女王i
猫巷女王i 2020-12-02 14:34

So if i have a ul with 100 li\'s should there be ng-clicks in each li or is there a way to bind the event to the ul and delegate it to the li\'s kind of what jquery does? Wo

4条回答
  •  情书的邮戳
    2020-12-02 15:18

    Working off of jm-'s example here, I wrote a more concise and flexible version of this directive. Thought I'd share. Credit goes to jm- ;)

    My version attempts to call the function name as $scope[ fn ]( e, data ), or fails gracefully.

    It passes an optional json object from the element which was clicked. This allows you to use Angular expressions and pass numerous properties to the method being called.

    HTML

    
    

    Javascript

    Controller Method

    $scope.handleMenu = function($event, data) {
      $event.preventDefault();
      $scope.activeLinkId = data.linkId;
      console.log('handleMenu', data, $scope);
    }
    

    Directive Constructor

    // The delegateClicks directive delegates click events to the selector provided in the delegate-selector attribute.
    // It will try to call the function provided in the delegate-clicks attribute.
    // Optionally, the target element can assign a data-ng-json attribute which represents a json object to pass into the function being called. 
    // Example json attribute: 
  • // Use case: Delegate click events within ng-repeater directives. app.directive('delegateClicks', function(){ return function($scope, element, attrs) { var fn = attrs.delegateClicks; element.on('click', attrs.delegateSelector, function(e){ var data = angular.fromJson( angular.element( e.target ).data('ngJson') || undefined ); if( typeof $scope[ fn ] == "function" ) $scope[ fn ]( e, data ); }); }; });

    I'd love to hear feedback if anyone wishes to contribute.

    I didn't test the handleMenu method since I extracted this from a more complex application.

提交回复
热议问题