Search code examples
javascriptangularjsangularjs-directivedom-eventsangularjs-ng-click

Automatically pass $event with ng-click?


I know that I can get access to the click event from ng-click if I pass in the $event object like so:

<button ng-click="myFunction($event)">Give me the $event</button>

<script>
  function myFunction (event) {
    typeof event !== "undefined" // true
  }
</script>

It's a little bit annoying having to pass $event explicitly every time. Is it possible to set ng-click to somehow pass it to the function by default?


Solution

  • Take a peek at the ng-click directive source:

    ...
    compile: function($element, attr) {
      var fn = $parse(attr[directiveName]);
      return function(scope, element, attr) {
        element.on(lowercase(name), function(event) {
          scope.$apply(function() {
            fn(scope, {$event:event});
          });
        });
      };
    }
    

    It shows how the event object is being passed on to the ng-click expression, using $event as a name of the parameter. This is done by the $parse service, which doesn't allow for the parameters to bleed into the target scope, which means the answer is no, you can't access the $event object any other way but through the callback parameter.