简体   繁体   中英

Creating custom mouseover in angular and passing $event to directive controller

I'm getting an error:

TypeError: Cannot read property 'x' of undefined

Heres my directive called tooltip :

.directive('tooltip', function() {
return {
    restrict: 'A',
    controller: function($scope) {
      $scope.enter = function(evt) {
          console.log('x: ' + evt.x + ', y: ' + evt.y);
      };
    },
    link: function(scope, element, attrs) {
      element.bind("mouseenter", function() {
        scope.$apply(attrs.tooltip);
      });

    }
}

});

HTML:

<svg>
  <g pathing tooltip="enter($event)">
   ...
  </g>
</svg>

You aren't passing the mouseenter event to the function.

This should work

element.bind("mouseenter", function(event) {
    scope.$apply(function(){
         attrs.tooltip(event);
     });
  });

Not sure why you don't just use call from scope:

$scope.enter(event) 

The function passed in via attrs.tooltip cannot be called directly like that.

You have to use the $parse service to invoke the function like this:

.directive('tooltip', function($parse) {
  return {
    restrict: 'A',
    controller: function($scope) {
      $scope.enter = function(evt) {
        console.log('x: ' + evt.x + ', y: ' + evt.y);
      };
    },
    link: function(scope, element, attrs) {
      var fn = $parse(attrs.tooltip);
      element.bind("mouseenter", function(event) {
        fn(scope, { $event: event });
      });
    }
  };
});

But, even better than that, why don't you just use the ng-mouseover directive

<g pathing ng-mouseover="enter($event)">
...
</g>

Example: http://plnkr.co/edit/hh0OCDWsRhYWcyhjvGiD?p=preview

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM