Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to get DOM element with ng-click

I have some element like :

<button ng-click="weirdFunction()">Pretty Button</button>

And function in controller :

$scope.weirdFunction = function(element) {
 console.log(element);
}

in console log I want to receive this DOM element. I tried to do this in several ways:

  1. <button ng-click="weirdFunction()" ng-model="button">Pretty Button</button>

    $scope.weirdFunction = function() { console.log($scope.button); }

  2. <button ng-click="weirdFunction(button)" ng-model="button">Pretty Button</button> $scope.weirdFunction = function(elem) { console.log(elem); }

  3. <button ng-click="weirdFunction($element)">Pretty Button</button> $scope.weirdFunction = function(elem) { console.log(elem); } But all attempts were failures. Where I'm wrong? How to get an element which clicked?

like image 257
YoroDiallo Avatar asked Aug 12 '16 09:08

YoroDiallo


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.

What is the use of NG-click?

The ng-click directive tells AngularJS what to do when an HTML element is clicked.


3 Answers

Please try following snippet.

var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
    $scope.weirdFunction = function(element) {
     console.log(element);
    }  
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myApp" ng-controller="myCtrl">
<button ng-click="weirdFunction($event.currentTarget)">Pretty Button</button>
 </div>
like image 82
Mohit Tanwani Avatar answered Oct 11 '22 11:10

Mohit Tanwani


Pass $event object to weirdFunction. $event.target gives the element on which the click was triggered.

<button ng-click="weirdFunction($event)">Pretty Button</button>
like image 22
Varun Singh Avatar answered Oct 11 '22 12:10

Varun Singh


I had this question now and concludes by creating this function

getElement($event){
    return $event.target || $event.srcElement || $event.toElement || $event.path[0];
};

At CanIUse it works everywhere.

like image 39
Luis Lobo Avatar answered Oct 11 '22 13:10

Luis Lobo