implementing a JSON array of integers within an Angular application

I am trying to import a JSON array of integers into scope.data in order to use it for creating D3 bars. However, I am facing issues as the array is not being utilized properly by D3 bars even though it is displayed when using {{data}} in the HTML. Can someone please assist me with this problem?

 angular.module('myApp', [])
//.controller('SalesController', ['$scope', function($scope, $http){
.controller('SalesController', function($scope, $http) {

/* $http.get('js/todos2.json')
.then(function(res){

      $scope.data = res.data;              
});*/

/*$http({method: 'GET', url: 'js/todos2.json'}).success(function(data)
{
$scope.data = data; // response data 
});*/

$http.get('js/todos2.json').success(function(data) {
   $scope.data = data;
});

/*$scope.data = [Math.random(),12,6,8,15];*/
/*$scope.data = 7*/
$scope.text = ('klopm');
 //parseInt(data)
}).directive('bars', function ($parse) {
  return {
     restrict: 'E',
     replace: true,
     template: '<div id="chart"></div>',
     scope:{data: '=data'},
     link: function (scope, element, attrs) {
       var data = scope.data;
       function drawBars() {
          var chart = d3.select('#chart')
         .append("div").attr("class", "chart")
         .selectAll('div')
         .data(data[0]).enter()
         .append("div")
         .transition().ease("elastic") //had la ligne bantli zayda na9ssa b3da pr l'affichage il faut savoir a quoi sert
         .style("width", function(d) { return d + "%"; })
         .text(function(d) { return d + "%"; });
       }
       drawBars();

     } 
  };
});

Answer №1

When retrieving information from a json file, the $scope.data variable may not be immediately populated. It is important to monitor its status before drawing a chart. In the directive definition, instead of directly invoking the drawBars() function, it is necessary to verify that the data exists. Consider implementing the following:

scope.$watch('data', function(){
    if(!scope.data) return; //If there is no data, do nothing

    //now call your draw function
    drawBars();
})

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

Query about Javascript/Node/JSON - why isn't this functioning properly?

I thought I had a good grasp on what I was doing until the process started getting jumbled. My code is being executed through Node, not a web browser. For some reason, it jumps to the prompt at the end of the while loop first and I'm not sure why tha ...

What is the process for choosing a table column by clicking on the "select" option?

Welcome to my project! Here is an example table that I'm working on. I have a question - how can I make it so that when I click on "choose me", the entire column is selected? Can you help me with this? <table> <tr> <th>plan A&l ...

What is the best way to randomly assign colors to my website links?

I'm trying to figure out why my code isn't functioning properly. Is there a mistake I'm not seeing? window.onload = function randomizeColor() { var links = document.getElementsByTagName('a'); var colors = new Array("green" ...

What is the mechanism for invoking functions defined with the arrow syntax in Angular?

Referencing this code snippet from the tutorial at https://angular.io/tutorial/toh-pt4, specifically within the hero.component.ts file: getHeroes(): void { this.heroService.getHeroes() .subscribe(heroes => this.heroes = heroes); } After analyz ...

Exploring TypeScript's type discrimination with objects

When working with TypeScript, type discrimination is a powerful concept: https://www.typescriptlang.org/play#example/discriminate-types But is it possible to achieve something like this? type A = {id: "a", value: boolean}; type B = {id: "b ...

The issue with the dispatch function not working in the Component props of React Redux

I'm struggling with my colorcontrol issue. I've been attempting to use this.props.dispatch(triggerFBEvent(fbID, method, params)) without success. Interestingly, it seems to work fine if I just use triggerFBEvent(fbID, method, params). However, I ...

Guide on how to optimize an ajax call in the browser to prefetch JSON data

One scenario I am dealing with involves initiating multiple ajax calls upon page load. The first call fetches data in JSON format from the server, and subsequent user interactions trigger further ajax requests that require database queries to process the J ...

calculating the total value of elements in a list the angular way

Here is a small example sample link where I am attempting to calculate the total of values in an angular manner: <div id="app" ng-app="myApp" ng-controller="myCtrl" ng-init="total = 0"> <ul> <li ng-repeat="x in myarr"> {{x.val}} ...

Inspecting Facebook links

Currently working on a website and interested in incorporating a feature similar to what Facebook has. I'm referring to the link inspector, but I'm not entirely sure if that's its official name. Allow me to provide an example to clarify my r ...

Is there a way to detect a class change using jQuery?

Below is an example of a div: <div id="components-reconnect-modal" class="components-connecting-show"> <div id="1"> <div id="2"> <div id="3"> <div id="4"> </div> The ID will remain constant, but the class will ...

Incorporate information into a JSON document while preserving its exact structure using Java

Whenever I use the method "public void fileWriter", my data gets incorrectly saved in the corresponding JSON file, making it impossible for me to retrieve them. What steps can I take to ensure that my data is stored in the correct JSON format? Here is the ...

Getting a 406 (Not acceptable) error when trying to perform an AJAX action in Rails 4

I am attempting to automatically refresh a specific partial view every 60 seconds on the homepage. To make it easier to manage, I have divided the actions into two routes. However, I am encountering an issue with the respond_to block and could use some ass ...

Fill a dropdown menu in HTML with data from a parsed JSON object array

Can someone help me with populating an html select element from the JSON data below? I can't figure out how to use a for each loop with this type of json data. Thanks! //JSON [{ "group": "US (Common)", "zones": [{ "value": "America/P ...

Sorting an object array by date is causing a problem

UPDATE: Finally cracked the code on this issue. I initially assumed that Date was interpreting the date ("29-04-2020") as DD-MM-YYYY, when it should actually be MM-DD-YYYY. For instance, here's an object array I'm working with: let t ...

The ng-model in Angular is unable to capture the initial input value on load

I am currently using a window onload script to obtain longitude and latitude data and pass them to hidden input values. $(function() { window.onload = getLocation; var geo = navigator.geolocation; function getLocation() { if (geo) { geo ...

What is the best way to find the difference between two time moments using Moment

Hello everyone, I could really use some assistance with Moment.js. I have two input fields, one labeled Start and the other labeled Stop. start = moment().format('LT'); // This works when I click on the play button stop = moment().format(' ...

What is the best way to remove a div card along with its content in a React application?

https://i.sstatic.net/IlXwE.gif Encountering an issue similar to the gif image provided. Upon deleting the first card, the content of the subsequent card is also removed. How can this be prevented? state = { data: '', todoCard: [ ...

Issues with the functionality of AngularJS router implementation

I have searched through various resources like Stack Overflow and other blogs, but unfortunately, I haven't been able to fix the routing issue in my AngularJS code. Although there are no error messages, the routing functionality doesn't seem to b ...

What is the best way to refresh a PHP function based on a JavaScript event?

I have a website where a div tag shows all the values from a SQL database using PHP. I want to reload this div tag with a JavaScript event, such as clicking on an HTML button. Is it possible to bring back all the values from the SQL database and display th ...

"Utilizing Vue Mixins on a global scale, but restricting their usage to local components

Is there a way to use a mixin in multiple components without having to constantly import and declare it? I've tried connecting the mixin object to a global variable using vue.prototype, but mixins are added to components before globals are accessible. ...