简体   繁体   English

在angular中创建自定义鼠标悬停并将$ event传递给指令控制器

[英]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 : 这是我的指令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: HTML:

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

You aren't passing the mouseenter event to the function. 您没有将mouseenter事件传递给该函数。

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. 通过attrs.tooltip传递的函数不能像这样直接调用。

You have to use the $parse service to invoke the function like this: 您必须使用$parse服务来调用如下函数:

.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 但是,甚至比这更好的是,为什么不使用ng-mouseover指令呢?

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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