Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>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- ;)</p> <p>My version attempts to call the function name as $scope[ fn ]( e, data ), or fails gracefully. </p> <p>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. </p> <p>HTML</p> <pre><code>&lt;ul delegate-clicks="handleMenu" delegate-selector="a"&gt; &lt;li ng-repeat="link in links"&gt; &lt;a href="#" data-ng-json='{ "linkId": {{link.id}} }'&gt;{{link.title}}&lt;/a&gt; &lt;/li&gt; &lt;/ul&gt; </code></pre> <p>Javascript</p> <p>Controller Method</p> <pre><code>$scope.handleMenu = function($event, data) { $event.preventDefault(); $scope.activeLinkId = data.linkId; console.log('handleMenu', data, $scope); } </code></pre> <p>Directive Constructor</p> <pre><code>// 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: &lt;li data-ng-json='{"key":"{{scopeValue}}" }'&gt;&lt;/li&gt; // 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 ); }); }; }); </code></pre> <p>I'd love to hear feedback if anyone wishes to contribute.</p> <p>I didn't test the handleMenu method since I extracted this from a more complex application.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload