Your thought to use an Angular ng-options
select menu is I believe a good one, because the way you are interspersing plain javascript with Angular does not seem like a particularly "Angular" way of going about the problem. For instance, in the spot where you are using onclick
, I would recommend going with Angular's ng-change
and putting the select
inside the controller.
Here is an example, building largely on your original, and using a bit more of an Angular approach to tackle the issue:
HTML
<div ng-app='nvd3TestApp'>
<div ng-controller="ExampleCtrl">
<select ng-init="selectedChart.chart = chartOptions[0]; updateChart()" ng-model="selectedChart.chart" ng-change="updateChart()" ng-options="c.name for c in chartOptions track by c.id"></select>
<nvd3-discrete-bar-chart data="exampleData" id="exampleId" width="800" height="400" tooltips="true" showXAxis="true" showYAxis="true">
<svg></svg>
</nvd3-discrete-bar-chart>
</div>
</div>
Javascript
angular.module("nvd3TestApp", ['nvd3ChartDirectives']);
function ExampleCtrl($scope) {
$scope.chartOptions = [{
id: 1,
name: "Option 1"
}, {
id: 2,
name: "Option 2"
}];
var d1 = [{
key: "Cumulative Return",
values: [
["A", -29.765957771107],
["B", 0],
["C", 32.807804682612],
["D", 196.45946739256],
["E", 0.19434030906893],
["F", -98.079782601442],
["G", -13.925743130903],
["H", -5.1387322875705]
]
}];
var d2 = [{
key: "Cumulative Return",
values: [
["A", -29.765957771107],
["B", 0],
["C", 32.807804682612],
["D", 196.45946739256],
["E", 0.19434030906893],
["F", -98.079782601442],
["G", -13.925743130903],
["H", -5.1387322875705]
]
}, {
key: "Cumulative Return2",
values: [
["A", 10.765957771107],
["B", 0],
["C", -32.807804682612],
["D", 96.45946739256],
["E", 0.19434030906893],
["F", -38.079782601442],
["G", -43.925743130903],
["H", -3.1387322875705]
]
}];
$scope.updateChart = function () {
if ($scope.selectedChart.chart === undefined || $scope.selectedChart.chart.id === 1) {
$scope.exampleData = d1;
}
if ($scope.selectedChart.chart !== undefined && $scope.selectedChart.chart.id === 2) {
$scope.exampleData = d2;
}
};
$scope.$on('tooltipShow.directive', function (event) {
//console.log('scope.tooltipShow', event);
});
$scope.$on('tooltipHide.directive', function (event) {
//console.log('scope.tooltipHide', event);
});
}
It is worth having a read of Scott Allen's post about using ngOptions.
http://odetocode.com/blogs/scott/archive/2013/06/19/using-ngoptions-in-angularjs.aspx
Regarding intializing select value, see this stackoverflow post:
How to have a default option in Angular.js select box