![](/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.