Search code examples
javascriptangularjs-directivenvd3.jsangularjs-nvd3-directives

Show current time in angular nvd3 line chart


I want to add a vertical "Now"-marker for the current time to a working time series line chart implemented with angular-nvd3-directives. Kind of like this: https://i.sstatic.net/X95T2.jpg

Previously I build this chart using pure d3.js and got it to work. So I tried to port my existing solution to a directive like so:

myApp.directive( 'nowMarker', function () {
  return {
      restrict: 'A',
      link: function (scope, element, attr) {
          var line = d3.svg.line()
            .interpolate("basis")
            // ####### this cannot work #######
            .x(function (d) { return x(d.t); })
            .y(function (d) { return y(d.value); });
            // ################################

          element.children()[0].append('svg:path')
            .attr("class", "NOW")
            .attr('d', line(scope.nowData))
            .attr('stroke', '#14022B')
            .attr('stroke-width', '1px')
            .attr('stroke-dasharray', ('5,5'))
            .attr('fill', 'none');
        }
    };
});

This is where I'm stuck. I don't know how to access the x and y scales of the angularjs-nvd3-directives chart.

The HTML is:

<nvd3-line-chart nowMarker ...>
</nvd3-line-chart>

and in my chart controller I have:

var now = new Date();
$scope.nowData = [
        {name: "NOW", t: now, value: 0}, 
        {name: "NOW", t: now, value: 100}
    ];

There are no error messages, simply nothing happens.

Any help is greatly appreciated. Thanks! Bennet


Solution

  • In case anyone else finds this useful:

    I ended up adding a "NOW" series to my chart data and assigning it a specific color.

    var tNow = new Date();
    var sNow = {
        key: "NOW",
        values: [
            [tNow, 0],
            [tNow, max]
        ],
        color: '#FFFFFF'
    };