Search code examples
javascriptangularjsd3.jsnvd3.jsangular-nvd3

angular-nvd3 gives various errors saying that d3.scale is undefined


I'm attempting a very basic angular-nvd3 proof of concept to try to get a demo chart to render based on the angular-nvd3 docs.

See the sample code at Plunker

I'm using the straight up Line Chart example but getting this error in the browser console:

angular.js:12477 TypeError: Cannot read property 'category20' of undefined
    at Object.nv.utils.defaultColor (nv.d3.js:987)
    at Object.nv.models.scatter (nv.d3.js:11844)
    at Object.nv.models.line (nv.d3.js:6467)
    at Object.nv.models.lineChart (nv.d3.js:6696)
    at Object.scope.api.updateWithOptions (angular-nvd3.js:95)
    at Object.scope.api.refresh (angular-nvd3.js:45)
    at Object.<anonymous> (angular-nvd3.js:437)
    at Object.fn (angular-nvd3.js:505)
    at n.$digest (angular.js:15826)
    at n.$apply (angular.js:16097)

I've played with various chart options trying to get to anything that would render a chart, but all variations seem to indicate that d3.scale is undefined inside of Object.nv somewhere. Yet, I'm just using the exact chart options and data from the angular-nvd3 examples.

Can anyone see what I'm doing wrong and how to get past this d3.scale being undefined when using angular-nvd3?


Solution

  • The problem is that the NVD3 library you're using is based on V3.x of the D3 library, but you're using v4.x of the D3 library. The ordinal scale API changed substantially between the two versions.

    Change

    <script src="https://cdnjs.cloudflare.com/ajax/libs/d3/4.1.1/d3.js"></script>

    to

    <script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.5.17/d3.js"></script>

    and that should fix the problem.

    I also had some issues getting angular to work with Plunkr so I had to modify your example a little, but the core change comes down to the 1-liner.

    http://plnkr.co/edit/bRAtP9xIiDaXnv04RAHu