Choose a chart from the dropdown menu and showcase it

I am facing a challenge in displaying two charts using a dropdown menu. I have attempted to achieve this using both JQuery and AngularJS, but I am encountering difficulties in making it work properly.

There are two charts that need to be displayed:

<div  ng-controller="ExampleCtrl">
    <nvd3-discrete-bar-chart
            data="exampleData"
            id="exampleId"
            width="800"
            height="400"
            tooltips="true"
            showXAxis="true"
            showYAxis="true">
        <svg></svg>
    </nvd3-discrete-bar-chart>

    <nvd3-discrete-bar-chart
            data="exampleData2"
            id="exampleId2"
            width="800"
            height="400"
            tooltips="true"
            showXAxis="true"
            showYAxis="true">
        <svg></svg>
    </nvd3-discrete-bar-chart>    
</div>

I intend to use a dropdown menu to toggle between the charts.

<select id="leave" onchange="leaveChange()">
  <option value="1">Second</option>
  <option value="2">First</option>

</select>

The function for selecting the chart is as follows:

function leaveChange() {
    if (document.getElementById("leave").value != "1"){
 document.getElementById("test").data="exampleData2";
    }     
    else{
        document.getElementById("test").data="exampleData";
    }        
}

If you prefer using Jquery instead, you can refer to this link for an example: http://jsfiddle.net/K3Lwj/3/

Answer №1

Your decision to incorporate an Angular ng-options select menu is commendable, as mixing plain JavaScript with Angular may not align with the typical "Angular" approach to problem-solving. Instead of using onclick, I suggest utilizing Angular's ng-change and placing the select within the controller.

Here is an example that expands on your original code, adopting a more Angular-centric strategy to address the issue:

http://jsfiddle.net/9GSNs/

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);
    });

}

For further insights into using ngOptions in AngularJS, check out Scott Allen's informative post:

If you're looking to set a default option in a select box in Angular.js, refer to this helpful Stack Overflow discussion: How to have a default option in Angular.js select box

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

jQuery - accessing a different class within the object

Let me explain the scenario: I have a website that will delve into 4 different subjects. Initially, I have 4 divs each representing the title of those subjects. For instance, <div><p> Physics </p></div> <div><p> Chem ...

Iterate through the call feature repeatedly, ensuring that each call has a different iteration number assigned to a variable within the

I have a situation where I need to call a certain feature (which has validations) multiple times within a loop. Currently, my code successfully calls the feature 3 times. * def xxx = """ function(times){ for(i=0;i<times ...

AngularJS: Troubleshooting ng-switch malfunction

I've been exploring various methods to show an HTML content block based on a selection. Instead of using ng-include, I have considered options like ng-if and ng-show/hide. I came across ng-switch and saw that it was working in a demo, but I'm f ...

I encountered a problem with React Native while attempting to update the state with a new value

As I work on developing my app using react native and firebase, I encountered an issue with the error message TypeError: undefined is not an object (evaluating 'this.state.desativado.push') when attempting to click the + button. https://i.sstati ...

Is there a way to launch only a single popup window?

Recently, I came across this piece of Javascript code which is causing me some trouble: function call() { popup = window.open('http://www.google.co.in'); setTimeout(wait, 5000); } function caller() { setInterval(call, 1000); } func ...

Utilizing GraphQL Global Object Identification with NestJS using the code-first strategy

Currently, I am trying to incorporate Global Object Identification as outlined in the GraphQL documentation into my NestJS project. 1.) First, I created a Node interface: import { ID, InterfaceType, Field } from '@nestjs/graphql' @InterfaceType ...

Paginating content without the need for a database

Seeking assistance on implementing pagination for displaying trading history API responses, without utilizing a database. Can anyone provide guidance and help with the necessary logic? Here is an excerpt of my code: <?php error_reporting(E_ALL) ...

What is the best way to limit the number of options displayed in the vue-multiselect

I'm looking to truncate multiple values on the vue-multiselect component. I attempted to override various classes without success, as shown in this example: .multiselect__content-wrapper { overflow-x: hidden; text-overflow: ellipsis; } ...

What is the most efficient way to check for the presence and truthiness of a nested boolean in Node.js?

There are instances where I must verify the deeply nested boolean value of an object to determine its existence and whether it is set to true or false. For instance, I need to ascertain if payload.options.save is assigned a value of false, yet I am uncert ...

After several interactions, the CSS files fail to load

I'm currently utilizing jQuery Mobile with 3 pages, and I've noticed that after navigating between the pages, the CSS is not being rendered properly. LoadCss.js $(document).on("pageinit",function(event) { $("#categoriesPage").on('pages ...

Navigating through an Angular 2 service

I'm struggling to retrieve an array from a JSON API and then loop through it. I can't seem to grasp how it all fits together. Any guidance would be greatly appreciated. This is what my service looks like: import {Injectable} from '@angular ...

Implementing Default Language in Next.js 14 for Static Export without URL Prefix: A Step-by-Step Guide

Currently, I am in the process of developing a website using Next.js 14, with the intention of exporting it as a static site for distribution through a CDN (Cloudflare Pages). The website I am working on requires support for internationalization (i18n) to ...

Change the order of numbering in ordered lists

I am seeking a way to change the ordering of an ordered list to be in descending order. You can view a live example here. Instead of having the counter span multiple ol elements, I would like the counter to reset after each ol. For the live demo, the des ...

Do closures truly behave like objects, or are they something else entirely? (It appears not)

Let me clarify right off the bat that I am not inquiring about how closures function, as I already have a grasp on that concept. What I am curious about is what data type should be assigned to closures. Essentially, a closure can be thought of as a record ...

Storing values from a content script into textboxes using a button press: a simple guide

I am new to creating chrome extensions and currently utilizing a content script to fetch values. However, I am facing difficulty in loading these values into the popup.html. Here is the code snippet: popup.html <head> <script src ...

What is the best way to rate a particular image?

while ($row = mysqli_fetch_array($result)) { echo ""; echo "<div id='img_div'>"; echo "<i class='fas fa-times'></i>"; echo "<img class='photoDeGallery' s ...

Issues with Pagination in a Dynamic Grid System when using Bootstrap DataTables

I am trying to display a user list in a grid format. Below are my PHP codes: Here is a simple PHP array: <?php $aso_arr = array( "1"=>"1", "2"=>"2", "3"=>"3", "4"=>"4", "5"=>"5", "6"=>"6", "7"= ...

Automatically expanding PrimeNG Turbotable rows

I am using a PrimeNg turbotable that has a row expansion feature enabled. I am looking for a way to automatically expand the rows by default when the table loads. Shown below is my code: HTML <p-table [columns]="cols" [value]="cars" dataKey="vin"> ...

When zoomed in, the div background gives off a crisp white appearance

When I zoom in on a div with a background color or border, it appears completely white. Strangely, this issue doesn't happen when I zoom in on the Facebook site. This picture illustrates the problem more clearly. What could be causing this issue? H ...

Leveraging $scope within ui-router resolve

Currently, I am utilizing ui-router resolve to fetch some data from a service. The challenge lies in needing to extract a value from the parent $scope before calling the service, as evidenced below. resolve: { contactService: 'contact ...