gpt4 book ai didi

javascript - 如何在AngularJS中检测鼠标事件的目标模型

转载 作者:搜寻专家 更新时间:2023-11-01 05:23:27 25 4
gpt4 key购买 nike

我在 svg 中绘制了几个元素(使用 ng-switch)并处理了它们的鼠标事件。 Controller 看起来像这样(有更多类型的元素和更多的鼠标事件要处理):

app.controller('MainCtrl', function($scope) {
$scope.elements = [
{ "type": "circle", "x" : 100, "y" : 200 },
{ "type" : "rect", "x" : 50, "y" : 20 }
];

$scope.mousedown = function(element, $event) {
$scope.msg = element.type;
};
});

在鼠标事件处理程序中,我需要鼠标事件目标的模型。我目前的解决方案是向每个 svg 元素添加 ng-mousedown="mousedown(element, $event)" ,这对于越来越多的元素类型来说很烦人。

    <g ng-switch="p.type">
<g ng-switch-when="circle">
<circle ng-mousedown="mousedown(p, $event)"></circle>
</g>
<g ng-switch-when="rect">
<rect ng-mousedown="mousedown(p, $event)"></rect>
</g>
</g>

有没有一种方法可以将 ng-mousedown 仅添加到根 svg 元素,并从 $event 属性($ event.target$event.srcElement 给我点击的 svg 元素,如何从中获取模型?)。

完整示例: http://plnkr.co/edit/nfgVSBBaeJ9EFKNjYEJn

最佳答案

是的,你可以使用 angular.element(...).scope().p 如下:

标记:

<svg xmlns="http://www.w3.org/2000/svg" ng-mousedown="mousedown2($event)">

JS:

$scope.mousedown2 = function($event) {
console.log(angular.element($event.target).scope().p);
});

查看 fork 的 plunk:http://plnkr.co/edit/7lGMphla42Chrg3X2NZl

关于javascript - 如何在AngularJS中检测鼠标事件的目标模型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20677303/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com