Please enable Javascript for better experience...
$event in angularJS
By Rahul Kumar Jha | Sep 30, 2015 | In Tips | Update: Jul 31, 2017 | Total Views [ 3015 ]
Taged In
(0 Like)

If you want to pass DOM object with ng-click, you cannot pass using "this" keyword as this keyword will not point to DOM object in this case. You should use $event as parameter in method in ng-click.

The Problem

I was writing some code in angularjs. I added a div element in my html page and tried to add ng-click event on this element. I added html5 data- attribute to the element and to get this attribute I passed "this" reference into the function. Suddenly, it started throwing error as this was not passing reference to div element. I tried several times but same error was throwing each time.

A Quick Solution

AngularJS has $event object which keeps reference of the event attached. You should use this object while adding reference instead of this keyword.

You can find element using $ attribute.

It will not work

<div data-id="div1" ng-click="ClickMe(this)">Click Me</div>

It will work

<div data-id="div1" ng-click="ClickMe($event)">Click Me</div>

Hope this helps you.

Share this

About the Author

Rahul Kumar Jha
Rahul Kumar Jha
Founder, Developer

Public profile: user/profile/99900001

Has working experience in different phases of Software Development Life Cycle (SDLC) in CMS, Gaming, Health Care and Financial Services domain using Agile pattern. Working experience in Design patterns, ASP.NET, MVC, ANGULAR, ANGULAR JS, Windows application, WCF, ADO.NET, SQL Server and Test Driven Development (TDD) environment with JQuery, JavaScript, N-Unit, Entity Frameworks, LINQ, Code Refactoring and Business Objects Models.

User's Comments

Please SignUp/Login to comment...

Or comment as anonymous...
* Name
* Email ID