我正在使用带有Angular的D3,我想在我的svg中插入一些文本元素,并在它们上面加ng-click
来启动我控制器中的某些功能。然而,ng-click
似乎从未发生过火灾。我已按照以下帖子中的建议尝试使用$compile
:
这些解决方案都不适合我。它显示$compile
正在执行某些操作,因为它会将属性role="button"
和tabindex="0"
附加到我的元素中,如下所示:
之前 $compile
:
<svg>
<text y="30" cursor="pointer" ng-click="alert('clicked')">CLICK ME</text>
</svg>
之后 $compile
:
<svg>
<text y="30" cursor="pointer" ng-click="alert('clicked')" role="button" tabindex="0">CLICK ME</text>
</svg>
我想知道页面上的某些内容是否可能会窃取点击事件?似乎angular已经在根html元素中添加了一个click处理程序。
之前我从未注意到这一点这是我的指令代码
.directive('clickMe', function ($compile) {
return {
restrict: 'A',
link: function (scope, element, attributes) {
var svg = d3.select(element[0])
.append('svg');
svg.append('text')
.text('CLICK ME')
.attr('y', '30')
.attr('cursor', 'pointer')
.attr('ng-click', 'alert(\'clicked\')');
var compiledSvg = $compile(svg.node())(scope);
element[0].children[0].replaceWith(compiledSvg[0]);
})
使用D3和Angular我使用的版本的jsfiddle说明了问题:https://jsfiddle.net/soultrip/604pts5v/3/
答案 0 :(得分:2)
我认为alert
不在您的模板范围内。相反,在指令范围内创建一个方法,并在ngClick
上调用该方法。
var myApp = angular.module('myApp', []);
myApp.directive('myDirective', function($compile) {
return {
restrict: 'A',
link: function(scope, element, attributes) {
let svg = d3.select(element[0])
.append('svg');
svg.append('text')
.text('CLICK ME')
.attr('y', '30')
.attr('cursor', 'pointer')
.attr('ng-click', 'showAlert(\'clicked\')');
let compiledSvg = $compile(svg.node())(scope);
element[0].children[0].replaceWith(compiledSvg[0]);
scope.showAlert = function(message) {
alert(message);
};
}
}
});