Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 905
Elise Avatar asked Jan 13 '14 21:01

Elise


People also ask

Can we use NG-click and Onclick together?

For a single btn, it's ok to use ng-click or onclick in the ng-app . There is no difference between the two functions. For effective team work, you,d better to have an account with each other. In Angular apps, ng-click is recommended.

Can we put condition in NG-click?

We can add ng-click event conditionally without using disabled class.

Can Ng-click have two functions?

In this article, we will learn how to get many/multiple functions to the ng-click directive passed, in just one click. The key is to add a semi-colon (;) or a comma (,). All the functions must be separated by a (;) or a (, ). This syntax is supported by all the elements in the HTML.

What is the difference between Ng-click and Onclick?

Another significant difference between ng-click and onclick is the execution context. Code inside an onclick attribute executes against the global window object, while an expression inside of ng-click executes against a specific scope object, typically the scope object representing the model for the current controller.


2 Answers

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.

like image 131
Stewie Avatar answered Sep 18 '22 21:09

Stewie


Add a $event to the ng-click, for example:

<button type="button" ng-click="saveOffer($event)" accesskey="S"></button> 

Then the jQuery.Event was passed to the callback:

enter image description here

like image 21
Jeff Tian Avatar answered Sep 18 '22 21:09

Jeff Tian