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