I am currently working with D3 and Angular, trying to insert text elements into my svg and have an ng-click
event on them to trigger functions in my controller. Unfortunately, the ng-click
event does not seem to be firing at all. I have attempted to use $compile
as recommended in various posts:
- How do I use angularjs directives in generated d3 html?
- Angular ng-click's inside a dynamically created d3 chart are not working
Unfortunately, none of those solutions have worked for me. It seems that $compile
is making some changes because it adds the attributes role="button"
and tabindex="0"
to my element like this:
Before $compile
:
<svg>
<text y="30" cursor="pointer" ng-click="alert('clicked')">CLICK ME</text>
</svg>
After $compile
:
<svg>
<text y="30" cursor="pointer" ng-click="alert('clicked')" role="button" tabindex="0">CLICK ME</text>
</svg>
I'm starting to think that something else on the page might be intercepting the click event. It appears that Angular has added a click handler to the root HTML element, which is something I have not noticed before.
https://i.sstatic.net/LViEa.png
This is the directive code I am using:
.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]);
})
Here is a jsfiddle showcasing the issue with the versions of D3 and Angular I am using: https://jsfiddle.net/soultrip/604pts5v/3/