简体   繁体   中英

ngIf inside custom directive and $watch

I'm using d3.js to create a simple graph. When I hover over a circle, I want to see some information pop up in a tooltip. All the code for the graph is in a custom directive, and when data is loaded (I'm using scope.$watch), I draw the graph no problem.

The problem occurs with the tooltip. I want to use ng-if to only show certain things if data exists for them, but it's not working. I don't know if there's a scoping issue, but here's the code for the tooltip. Note that it's inside the scope.$watch inside the link function of the custom directive:

      var showPopup = function(el, data) {
        var svgPosition = $('#chart').position(),
          offsetTop = svgPosition.top,
          offsetLeft = svgPosition.left,
          circle = d3.select(el),
          top = parseInt(circle.attr('cy'), 10),
          left = parseInt(circle.attr('cx'), 10),
          r = parseInt(circle.attr('r'), 10),
          pop = d3.select('#tooltip');
        pop
          .html(
            '<div class="tooltip-wrapper">' +
              '<span class="number">' + data.week + '.</span>' +
              '<span class="person"><a href="#/person/' + data.name + '">' + data.name + '</a></span>' +
              '<ul>' +
                '<li ng-if="data.numbers">Numbers: ' + data.numbers + '</li>' +
              '</ul>' +
            '</div>'
          )
          .style('opacity', 1)
          .style('top', top + offsetTop + margin.top + 'px')
          .style('left', left + offsetLeft + margin.left + 'px');
      };

The li is still showing up as Numbers: undefined. Any ideas how to get this working? Thanks.

Have you tried something like this instead of the ng-if?

var html = '<div class="tooltip-wrapper">' +
  '<span class="number">' + data.week + '.</span>' +
  '<span class="person"><a href="#/person/' + data.name + '">' + data.name + '</a></span>' +
  '<ul>';

if (data.numbers) {
  html += '<li ng-if="data.numbers">Numbers: ' + data.numbers + '</li>';
}

html += '<li ng-if="data.numbers">Numbers: ' + data.numbers + '</li></ul></div>';

pop.html(html);

This is off the top of my head btw, I haven't tested it...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM