![](/img/trans.png)
[英]Custom ng-enter directive not passing $event from html to the controller
[英]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>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.