Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to detect the model of the target of a mouse event in AngularJS

I draw several elements in svg (using ng-switch) and handle mouse events on them. The controller looks like this (there are much more types of elements and more mouse events to handle):

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;  
  };
});

Inside the mouse event handler, I need the model of the target of the mouse event. My current solution is to add ng-mousedown="mousedown(element, $event)" to each svg element, which is annoying for a growing number of element types.

    <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>

Is there a way to add ng-mousedown only to the root svg element and retrieve the model of the clicked element from the $event properties ($event.target or $event.srcElement gives me the clicked svg element, how to get the model from this?).

Complete example: http://plnkr.co/edit/nfgVSBBaeJ9EFKNjYEJn

like image 764
hansmaad Avatar asked Mar 22 '23 06:03

hansmaad


1 Answers

Yes, you can use angular.element(...).scope().p as follows:

Markup:

<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);
});

See forked plunk: http://plnkr.co/edit/7lGMphla42Chrg3X2NZl

like image 182
Nikos Paraskevopoulos Avatar answered Apr 07 '23 20:04

Nikos Paraskevopoulos