Maximizing the efficiency of Angular Directives combined with JSON

Looking for an efficient method to factorize an Angular Directive designed for displaying charts.

After exploring various solutions, I discovered a neat way to implement a directive that showcases a single chart flawlessly.

How can I utilize the same directive for showcasing different charts? Each chart requires a JSON object containing settings and data for rendering.

Avoid cluttering the Angular View with excessive JSON input passed through the directive.

Specifics:-

  • Every chart shares certain key/value pairs that can be included in the directive.
  • How do I integrate chart-specific key & value pairs into each directive?

E.g. - One chart featuring green bars while the other displays red lines.

Angular Directive

(function () {

    'use strict';

    angular
        .module("analytics")
        .directive("angularDirectiveAmcharts", angularDirectiveAmcharts);

    function angularDirectiveAmcharts() {

        var directive = {
            link: link,
            restrict: 'A',
            replace: true,
            scope: {
                chartdata: '=',
                type: '=',
                customstyle: '@',
                chartsettings: '=',
                chartid: '@'
            },
            template: '<div id="{{ chartid }}" style="{{ customstyle }}"></div>'
        };

        return directive;             


        function link(scope, elem, attrs) {
            AmCharts.makeChart(scope.chartid, {
                "type": "serial",
                "categoryField": "date",
                "autoMarginOffset": 10,
                "marginRight": 20,
                "marginTop": 20,

                 //Omitted some key-value pairs for brevity

                "dataProvider": scope.chartdata
            });


        }
    }
})();

View

<div class="chartarea" ng-controller="pcController as vm">

    <div angular-directive-amcharts chartid="chartdiv" chartdata="vm.chart_data"></div>

</div>

Prioritizing maintainability as there will be numerous modifications post-internship completion.

Answer №1

Some of the code in this answer is inspired by another solution

If you want a consistent configuration for all your chart directives, consider using a service. With this approach, you can set a standard configuration once and then customize it as needed when creating each directive. This simplifies making minor adjustments in your controller.

While not mandatory, you can bind additional configurations to the directive:

<div ng-controller="myCtrl">
    <my-chart></my-chart>
    <my-chart config="conf"></my-chart>
</div>

Customized configuration in the controller:

myapp.controller('myCtrl', function ($scope) {
    $scope.conf = {
        graphs: [{ type: 'column' }]
    };
});

A service for default settings (using jQuery's method for deep merging objects):

myapp.service('chartService', function () {
    this.defaultConfig = {
        "type": "serial",
        // simplified object for better readability
    };
    this.getConfig = function (mergeObj) {
        return $.extend(true, {}, this.defaultConfig, mergeObj);
    }
});

The data is fetched using another service and added to the merged configuration:

var config = chartService.getConfig(scope.config || {});
config.dataProvider = dataProvider.getData();
chart = AmCharts.makeChart(element[0], config);

You can view an example in this JSFiddle.

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

What is the process for automatically storing a JSON object in a database?

I'm working with a massive Json object that I need to store in a nosql database. I have two main questions: First of all, how can I create the database schema based on this Json object? Secondly, is there any method to automatically insert this obje ...

Exploring the execution of internal methods within an Angular service

My service is a simple one for Shoes app.factory('Shoes', function() { function x() {return 12;} function y() {return x();} return { x: x, y: y } }) I am trying to verify if the method x gets called when I invoke ...

Creating nested JSON objects with identical keys in JavaScript

{"func" : "sprint", "nest" : {"func" : "walk", "nest": {"func" : "run"}}} The provided code snippet demonstrates the structure of a nested JSON object. These nested objects can vary in complexity, from a single object to multiple levels of nesting. The g ...

What makes running the 'rimraf dist' command in a build script essential?

Why would the "rimraf dist" command be used in the build script of a package.json file? "scripts": { "build": "rimraf dist ..." }, ...

Error in AJAX Codeigniter - No file selected for upload - Steps to successfully pass the file using AJAX

Currently, I am attempting to upload images using an AJAX call with Codeigniter: This is my View: <?php echo form_open_multipart('upload/do_upload'); ?> <input type="file" name="userfile" id="userfile" size="20" ...

"Struggling with Mongoose's Inaccurate Value Saving

When I attempt to create an object from a post request, I notice that the fields coming from the request body are being set to the field name itself. Strangely, I am not receiving any errors but the JSON object I expect in the response is not what I am get ...

Sending files correctly using Node.js

Here is a simple middleware to consider: (req, res, next) => { const stream = fs.createReadStream(req.filePath) await new Promise((resolve, reject) => stream .on('error', reject) .on('end', resolve) .pipe(res ...

Update the color of the header background in an HTML table to match its original shade

Whenever a selection is made from the dropdown menu, a script triggers to change the background color of the selected number in the table header. I'm trying to figure out how to revert the background color back to its original state after making a ne ...

The primary objective is to ensure that the input remains contained within the code

I am having issues with my PhoneGap 2.2.0 and Android 4.0.4 application. Whenever I click the input, a div opens above it. Here is a snippet of My Input and My Div: <input type="text" onclick="OpenDiv();" id="MyInput" /> <div id="MyDiv"& ...

Learn the process of incorporating the ternary operator within a return statement to output an array

I'm currently working with React 16.0. There's a scenario where I need to conditionally return elements, like the example below. import React from 'react'; export default class App extends React.PureComponent { render () { ...

Is the removal of the Vue-Router link happening when you click on the top app bar icon in Google Material

Review of the following code snippet: <!DOCTYPE html> <html> <head> <title>test</title> <meta content='width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0' name='vie ...

execute a synchronous function within a promise

Recently diving into the world of JavaScript and asynchronous operations, I found myself working on a Node.js router with Express that pulls weather data from MongoDB using Mongoose. This data is collected from various sites at 15-minute intervals and proc ...

Have you transitioned from using hover in jQuery to writing code in Backbone

I am looking to translate this code into the backbone event model without relying directly on jQuery. $(".class").is(":hover") In attempting to achieve this in my view, I have tried registering events (mouseenter, mouseleave), but it seems that these eve ...

Vue3 CheckBox Component: A versatile option for interactive user interfaces

Struggling with incorporating checkboxes into a separate component. I have a child component with a basic card template and checkbox - essentially, a product list where each card should have a checkbox for deletion. Currently, as I loop through an array to ...

Using Node.js to update information within Firebase

Here's a problem I'm facing: I have a cron job running in Node.js that sends data to a Firebase database every minute. The issue is, even when there are no changes, the database still receives information. Take a look at my code snippet below: l ...

Enforcing Single Menu Accessibility in React: Only One Menu Open at a Time

Just starting out with React and JavaScript, so please bear with me for any formatting issues or lack of knowledge on best practices. I'm using Tailwind UI for my website, which includes navigation menus that require JavaScript to open and close. I h ...

What is the best way to extract the property name from the AJV output in order to effectively translate validation errors into user-friendly

I am currently utilizing the AJV library for input validation in my nodejs express api. I'm facing an issue with extracting the property name associated with each error object within the returned array. [{ instancePath: '', schemaPath: & ...

Guide to incorporating HTML within React JSX following the completion of a function that yields an HTML tag

I am currently working on a function that is triggered upon submitting a Form. This function dynamically generates a paragraph based on the response received from an Axios POST request. I am facing some difficulty trying to figure out the best way to inje ...

A pair of dropdowns with a single onchange event

Hey there! I'm looking to make my ajax function work only when both dropdown menus have values selected. And I'm wondering how to pass the data from both dropdowns. Here's what I have so far: SCRIPT <script> function getState(val) { ...

Table created by Javascript is malfunctioning

Is there an obvious mistake to be found? Why isn't the Javascript generated table from the showResults function displaying on my HTML page? This issue always arises when I need to include a large number of literal values... I would also welcome feedba ...