我有一些元素:
<button ng-click="weirdFunction()">Pretty Button</button>
在控制器中运行:
$scope.weirdFunction = function(element) {
console.log(element);
}
在控制台日志中我希望收到这个DOM元素。我尝试过几种方式:
<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);
}
但所有尝试都失败了。我哪里错了?如何获得点击的元素?
答案 0 :(得分:2)
将$ event对象传递给weirdFunction。 $ event.target给出触发点击的元素。
<button ng-click="weirdFunction($event)">Pretty Button</button>
答案 1 :(得分:1)
请尝试以下代码段。
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
$scope.weirdFunction = function(element) {
console.log(element);
}
});
&#13;
<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>
&#13;
答案 2 :(得分:0)
我现在有这个问题,并通过创建此函数结束
getElement($event){
return $event.target || $event.srcElement || $event.toElement || $event.path[0];
};
在CanIUse,它可以在任何地方使用。