Using AngularJS to send a large JSON file to a directive

It seems like I have identified the issue with the chart not displaying properly. The problem is most likely due to the fact that I am loading a large JSON object from a RESTful server and passing it to a directive for chart generation before the JSON has finished downloading completely.

The JSON file is nearly 1mb in size and I am fetching it like this:

Within the Controller:

dataArchive.get().then(function(result){
    $scope.getData = result;
});

And in the HTML:

<divng-controller="archiveCtrl">
    <data-graph get-archive-data="getData"></data-graph>
</div>

Within the directive:

var chart = function(data){
     var createchart = new AmCharts.makeChart("chartdiv", {
          //
     });
}

var linker = function(scope, element, attrs){
    scope.$watch('data', function(){
        chart(scope.data);
    });
}

directives.directive('dataGraph', function(){
    return {
        restrict: 'E',
        replace: false,
        scope: {
            data: '=getArchiveData'
        },
        template: '<div id="chartdiv"></div>',
        link: linker
    };
});

Due to this, the directive template may load with empty content, causing the chart to not generate properly. What would be the best way to solve this issue?

Answer №1

Utilizing $watch correctly should trigger the charting function, but I recommend exploring other methods to determine the most effective approach.

Initially, the watch function will execute during the initial directive linking even if the data is not present, resulting in a call to the chart function with undefined, potentially displaying an empty chart. Subsequently, when the data is fetched, the $watch will trigger again. However, there may be issues with the charting function when called multiple times. Consider adding the following conditional check:

scope.$watch('data', function(){
  if (!scope.data) return
  chart(scope.data);
});

Another method that has worked for me when awaiting the resolution of a variable is to use $observe without including the variable in the directive's scope:

<data-graph get-archive-data="{{ getData }}"></data-graph>

var linker = function(scope, element, attrs){
  attrs.$observe('getArchiveData', function(data){
    if (!data) return;
    chart(data);
  });
}

directives.directive('dataGraph', function(){
  return {
    restrict: 'E',
    replace: false,
    // Remove below  
    //scope: {
    //    data: '=getArchiveData'
    //},
    template: '<div id="chartdiv"></div>',
    link: linker
  };
});

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

Transforming this JavaScript code to be less intrusive by implementing an event listener for an unidentified ID

As I work on enhancing the functionality of this user interface, I've encountered a challenge with two tabs that require a proper event listener to ensure my JavaScript functions smoothly. This obstacle has been hindering my progress, but as I delve i ...

Learn how to effortlessly update models by integrating AngularJS with Django and Django Rest Framework

Here is a JSON representation of a post based on its ID: http://127.0.0.1:8000/update/1?format=json {"title": "about me", "content": "I like program", "created": "2014-11-29T18:07:18.173Z", "rating": 1, "id": 1} I am attempting to update the rating ...

Error message "Sphere undefined" encountered in ThreeJS Water2 example

I've been experimenting with setting up the basic ThreeJS Water2 example that can be found here: You can access the source code here: https://github.com/mrdoob/three.js/blob/master/examples/webgl_water.html The process appears simple at first glance ...

What are some effective methods for resetting a state in @ngrx/store?

Lately, I've been grappling with a problem that's been on my mind for the past few days. Our team is developing an Angular 2 application, and my task involves creating a wizard for users to complete a form. I've successfully set up the dat ...

Custom JavaScript code in Bootstrap Navbar Toggler results in closing the menu when a dropdown is clicked

As a newcomer to JavaScript, I am currently learning the language while working on a website. I have customized a template that I found online but am struggling with the JS code that I'm not very familiar with. Here's my issue: When using the na ...

Looking to showcase initial API data upon page load without requiring any user input?

Introduction Currently, I am retrieving data from the openweatherAPI, which is being displayed in both the console and on the page. Issue My problem lies in not being able to showcase the default data on the frontend immediately upon the page's fir ...

Switching between components in vue.js: A beginner's guide

In my project, I created a Dashboard.vue page that consists of three child components: Display, sortBooksLowtoHigh, and sortBooksHightoLow. The Dashboard component also includes a select option with two choices: "Price: High to Low" and "Price: Low to High ...

What is the best way to arrange map items using justify-content-around for optimal display?

I'm currently iterating through products using the map function, but I'm having trouble getting the justify-content-around property to apply. I am working on a React project with Bootstrap 4 integrated. Below is the code snippet: {props.product ...

The issue of actions failing to flow from sagas to reducers in React.js

Upon user login, the success response is received but the action is not passed to the reducer. Strangely, during user registration, everything works smoothly. //saga.js import { put, takeEvery, all, call } from 'redux-saga/effects'; import {getRe ...

Synchronously executing Twitter posts

Hello there! I've been using this code found here to embed Twitter posts on my website. It's been working perfectly on certain pages, like in the forums, but I've run into an issue while browsing through user profiles. The post history for e ...

Combine the remaining bars by stacking the highest one on top in Highchart

Making use of stacking to display the highest value as the longest column/bar, with smaller values being merged within the highest one, can create a more visually appealing stack chart. For example, when looking at Arsenal with values of 14 and 3, ideally ...

Localization for Timeago JS Plugin

Currently, I have integrated the jQuery TimeAgo plugin into my project and included the following code snippet for localization in Portuguese: // Portuguese jQuery.timeago.settings.strings = { suffixAgo: "atrás", suffixFromNow: "a partir de agora", ...

Discovering how to use the selenium-webdriver npm to navigate to a new window from a target="_blank" attribute

While trying to create a collection of selenium tests, I encountered an obstacle with the javascript selenium-webdriver npm package. One specific test involves selenium verifying that a target="_blank" link functions properly by checking the content of th ...

Shiny silver finish using three.js technology

I have recently started exploring three.js and am attempting to replicate a cube that looks like this: https://i.sstatic.net/CO9Eq.jpg One aspect I'm struggling with is creating the material for my cube. The material appears to be a silver polished fi ...

Adjust the size of the leaflet popup with Vue2Leaflet's l-popup component

I've been working on programming a web application and incorporating leaflet to showcase a map. I've set up markers and popups that show up when the markers are clicked. However, I've noticed that the popups look a bit odd right now – the ...

Transforming JSON data into a pandas dataframe

Here is the data in JSON format: { "current": [ [ 0, "2017-01-15T00:08:36Z" ], [ 0, "2017-01-15T00:18:36Z" ] ], "voltage": [ [ 12.891309987, "2017-01-15T00:08:36Z" ], [ 12.8952162 ...

What is the best way to pass a variable and its corresponding state-updating function as a prop in a React component?

Considering I have a variable defined as follows: const [APIKey, setAPIKey] = useState([]) Is it possible to group these together into a single variable and then pass it as a prop? const passAPI = {APIKey, setAPIKey} Here is my approach to passing it alo ...

What is the best way to pass my session token information between various JavaScript files on the server?

Here's the current status of my session tokens on the server: In my server.js file: app.use( session({ secret: "{ ...

Guide to making two text boxes with SimpleDialog in jQuery Mobile

I came across the link below, but unfortunately it's not working for me. jQuery Mobile SimpleDialog with two Inputs? Is there anyone who can assist me after reviewing the code snippet provided below? <script type="text/javascript> ...

The callback function is no longer accepted by the Model.prototype.save() method

Even after exploring various questions and answers on StackOverflow, I am still facing a persistent issue. The problem revolves around an app designed for inputting items and pushing them to a MongoDB database. However, I keep encountering errors. I am in ...