angular-nvd3: $scope.api returns undefined
When I run the $scope.api functions in my code or in the plunkers, I get a type error:
TypeError: Cannot read property ‘refresh’ of undefined at Object.<anonymous> (http://localhost:9000/app/d3loader/d3loader.controller.js:21:17)
What am I doing wrong?
Here’s the code: HTML excerpt:
<nvd3 options="options" data="data" api="api"></nvd3>
JavaScript:
var app = angular.module('plunker', ['nvd3']);
app.controller('MainCtrl', function($scope) {
console.log('scope api:', $scope.api); //undefined
$scope.api.refresh(); //Cannot read property 'refresh' of undefined
$scope.options = {
chart: {
type: 'pieChart',
height: 450,
donut: true,
x: function(d){return d.key;},
y: function(d){return d.y;},
showLabels: true,
pie: {
startAngle: function(d) { return d.startAngle/2 -Math.PI/2 },
endAngle: function(d) { return d.endAngle/2 -Math.PI/2 }
},
transitionDuration: 500,
legend: {
margin: {
top: 5,
right: 70,
bottom: 5,
left: 0
}
}
}
};
$scope.data = [
{
key: "One",
y: 5
},
{
key: "Two",
y: 2
},
{
key: "Three",
y: 9
},
{
key: "Four",
y: 7
},
{
key: "Five",
y: 4
},
{
key: "Six",
y: 3
},
{
key: "Seven",
y: .5
}
];
});
About this issue
- Original URL
- State: closed
- Created 10 years ago
- Comments: 19 (1 by maintainers)
@owaaa: I kind of figured a work around. Stumbled on it, more like. When you set the api, instead of creating it as $scope.api, define it as $scope.xxx.api. This somehow worked for me. I’m not sure why though.
@srujanrouthu great suff… still useful…
For anyone else who comes here and looks at @srujanrouthu’s comment, this could be because you are using “controller as” syntax. @ginna-baker’s original issue is using $scope, which should imply that she isn’t using “controller as” syntax.
I’ve fallen trap to the same issue she had, however the trick was taking @srujanrouthu’s comment and applying the api attribute to my “controller as” object.
Following is a variable I defined in my controller during intialization:
$scope.rc = {}Following is my DOM element
<nvd3 options="options" data="data" api="rc.api" class="with-3d-shadow with-transitions"></nvd3>Following is the code accessing the chart API
$scope.rc.api.getScope().chart.xAxis.tickValues(function () { return arr });or
$scope.rc.api.refresh();$scope.api is
undefinedbecause you try to use it before directive is created. Try to wait for some time that directive was created: