Tarun Dugar Tarun Dugar - 7 months ago 152
Javascript Question

D3: Uncaught ReferenceError: stream_layers is not defined

I was using nvd3.js to create a simple stacked bar chart as described here

I added the code mentioned in the link in an angular directive as follows:

app.directive('stackBar', function() {
return {
restrict: 'A',
link: function(scope, element, attrs) {
nv.addGraph(function() {
var chart = nv.models.multiBarChart()
/*.transitionDuration(350)*/
.reduceXTicks(true) //If 'false', every single x-axis tick label will be rendered.
/*.rotateLabels(0) */ //Angle to rotate x-axis labels.
.showControls(true) //Allow user to switch between 'Grouped' and 'Stacked' mode.
.groupSpacing(0.1) //Distance between each group of bars.

chart.xAxis
.tickFormat(d3.format(',f'));

chart.yAxis
.tickFormat(d3.format(',.1f'));

d3.select(element[0])
.datum(exampleData())
.call(chart);

nv.utils.windowResize(chart.update);
return chart;
});

//Generate some nice data.
function exampleData() {
return stream_layers(3,10+Math.random()*100,.1).map(function(data, i) {
return {
key: 'Stream #' + i,
values: data
};
});
}
}
}
});


Here's my HTML:

<td class="centered" colspan="5">
<div stack-bar>

</div>
</td>


But, I am getting the following error:

Uncaught ReferenceError: stream_layers is not defined


Any idea where I am going wrong?

Also, 'transitonDuration' was also not working so I commented it out. I initially thought, this maybe some problem related to the version of d3, but I am using the latest version and still the problem persists.

EDIT:

Huang Feng's answer helped me get rid of the error. But instead of getting any chart I am getting a lot of text. Here's a screenshot:

enter image description here

Any idea why?

Also, the directive is in an ng-repeat, and thats why there are multiple rows as in the screenshot.

Answer

This is because you don't define the stream_layers function, and it's also not a function in nvd3 lib. It's defined here:

http://nvd3.org/assets/js/data/stream_layers.js

If you want to use it, you should include this lib in the html like:

<script src="../stream_layers.js"></script>

If you want a detail example, here is one for your reference:

http://bl.ocks.org/mbostock/3943967