繁体   English   中英

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

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

我收到一个错误:

TypeError: Cannot read property 'x' of undefined

这是我的指令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>

您没有将mouseenter事件传递给该函数。

这应该工作

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

不知道为什么不只使用范围调用:

$scope.enter(event) 

通过attrs.tooltip传递的函数不能像这样直接调用。

您必须使用$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 });
      });
    }
  };
});

但是,甚至比这更好的是,为什么不使用ng-mouseover指令呢?

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

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

暂无
暂无

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

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