Implementing the currentTarget Property
In this approach, we will use the currentTarget property of an event to get the original element that triggered the click event from the ng-click directive. The following steps will be followed:
- Create an AngularJS project using the CDN: Create an AngularJS project using the AngularJS CDN. You can name the app “my-app”.
- Include the Angular CDN script and create a base layout: Include the Angular CDN script in the HTML file and add a div and button inside the body tag.
- Add the AngularJS controller to the script: Create an AngularJS controller, and inside the controller, access the event’s currentTarget property to get the original element that triggered the ng-click event.
Example: This example illustrates the basic implementation to get the original element from the ng-click Directive.
HTML
<!DOCTYPE html> < html > < head > < script src = "https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js" > </ script > < script > angular.module('myApp', []).controller( 'gfgCtrl', function ($scope) { $scope.myFunction = function (event) { const originalElement = event.currentTarget; console.log('originalElement!', originalElement); }; }); </ script > </ head > < body style = "text-align: center;" > < div ng-app = "myApp" ng-controller = "gfgCtrl" > < div ng-click = "myFunction($event)" > < button >Click me</ button > </ div > </ div > </ body > </ html > |
Output: The output should log the original element that triggered the ng-click event to the console.
How to get original element from ng-click in AngularJS ?
In AngularJS, we can get the original DOM element that fired the ng-click event using the event’s currentTarget property. Getting the event’s currentTarget can be useful when we want to track an element’s activity, in this case, whether and how many times a particular element is clicked, or we want to perform a certain operation if a particular element in the DOM gets clicked. In this article, we will see how to get the original element from ng-click in AngularJS.
There are 2 approaches to get the original element by implementing the ng-click Directive:
Table of Content
- Implementing the currentTarget Property
- Implementing the target Property