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:
<button ng-click="weirdFunction()" ng-model="button">Pretty Button</button>
$scope.weirdFunction = function() {
console.log($scope.button);
}
<button ng-click="weirdFunction(button)" ng-model="button">Pretty Button</button>
$scope.weirdFunction = function(elem) {
console.log(elem);
}
<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?
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.
We can add ng-click event conditionally without using disabled class.
The ng-click directive tells AngularJS what to do when an HTML element is clicked.
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>
Pass $event object to weirdFunction. $event.target gives the element on which the click was triggered.
<button ng-click="weirdFunction($event)">Pretty Button</button>
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With