Is passing an $event necessary in ng-click

时间:2016-07-11 20:04:07

标签: javascript angularjs

I am new to AngularJS and exploring event handlers. I am going over an existing code base and had no idea why $event is being passed. This is what the html looks like

<p><a ng-click="packBtnClick($event)" href="#" title="">[[btnAction]]</a></p>

And in the controller,

$scope.packBtnClick = function($e){
  $e.preventDefault();
  if($scope.packAvailable){
     addPackIntoCart();
   }
  else{
    //some other code. 
 };

The only purpose of passing in an event here is to preventDefault behavior.
My question is - is it really necessary to pass in the $event?

1 个答案:

答案 0 :(得分:3)

It is necessary if you want to call preventDefault and unnecessary otherwise. If you do not need to call anything exposed by $event, you can safely remove it since not passing it in will not prevent the event from occurring.

You can find the $event documentation here. It is simply a wrapper for the jQuery event object when jQuery is present, or something similar when using jqLite. You can look at the event object for a full list of potentially exposed properties and functions. jqLite is not guaranteed to expose all of the same properties and functions, but it should be very close in nearly all scenarios.