Search code examples
angularjsd3.jsnvd3.jsangular-nvd3

Filter by range date for angular-nvd3 directive?


I create an nvd3 graph with the angular-nvd3 directive:

<nvd3 id="analytics-community" options="vm.community.options" data="vm.community.data" config="vm.graphConfig" class="with-3d-shadow with-transitions"></nvd3>

However it does not seem possible to filter the data attribute using |filter:something as it ends up looping infinitely and angular breaks with infinite loop error.

Graph options are setup with:

vm.graphOptions = {
    chart: {
        type: 'lineChart',
        height: 300,
        margin : {
            top: 50,
            right: 50,
            bottom: 50,
            left: 50
        },
        x: function(d) {
            return d3.time.format.iso.parse(d.key);
        },
        y: function(d) {
            return d.value;
        },
        useInteractiveGuideline: false,
        dispatch: {
            stateChange: function(e) { },
            changeState: function(e) { },
            tooltipShow: function(e) { },
            tooltipHide: function(e) { }
        },
        xScale: d3.time.scale(),
        xAxis: {
            axisLabel: 'Date',
            tickFormat: function (d) {
                return d3.time.format('%b %Y')(new Date(d));
            }
        },
        yAxis: {
            axisLabel: 'Count',
            tickFormat: function(d) {
                return d;
            }
        }
    }
};

And the data is set-up with:

vm.community.data = [
    {
        key: 'Members',
        values: vm.statsModel.registeredMembers
    },
    {
        key: 'Students',
        values: vm.statsModel.registeredStudents
    },
    {
        key: 'Alumni',
        values: vm.statsModel.registeredAlumni
    }
];

Where vm.statsModel.registeredMembers is like:

[
  {
    key: "2015-06-15",
    value: 458
  },
  {
    key: "2015-06-23",
    value: 459
  },
  {
    key: "2015-06-27",
    value: 460
  }
]

Any ideas?


Solution

  • Setting the xDomain in vm.graphOptions.chart worked:

    vm.graphOptions.chart.xDomain = [new Date(vm.selectedItem.date), dateToday]
    

    Where vm.selectedItem.date = new Date().setMonth(new Date().getMonth() - 6) for 6 months ago... and dateToday = new Date()

    So I just $watch for changes on vm.selectedItem which changes with a select box and update xDomain.