YoroDiallo YoroDiallo - 3 months ago 22
AngularJS Question

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?


Answer

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>