What is the proper way to incorporate scripts into my AngularJS controller?

I am encountering an issue that may be stemming from my incomplete understanding of AngularJS. My goal is to incorporate some JS scripts into my HTML.

<head>
<script src="https://code.highcharts.com/highcharts.js"></script>
<script src="https://code.highcharts.com/gantt/modules/gantt.js"></script>
<script src="https://code.highcharts.com/gantt/modules/exporting.js"></script>
<head>
<body>
    <div id="plandat"></div>
</body>

The challenge lies in utilizing both AngularJS and additional JavaScript together. Here's a snippet of how my controller appears.

angular.module('analyticsCtrl', ['rzModule', 'daterangepicker'])
  .controller('planDatController', function($templateCache, $scope, $http, $interval, $filter, uiGridGroupingConstants ){

Highcharts.ganttChart('plandat', {
title: {
    text: 'Plan Dat'
},

series: [{
    name: 'Project 1',
    data: [{
        id: 's',
        name: 'Start prototype',
        start: Date.UTC(2014, 10, 18),
        end: Date.UTC(2014, 10, 20)
    }, {
        id: 'b',
        name: 'Develop',
        start: Date.UTC(2014, 10, 20),
        end: Date.UTC(2014, 10, 25),
        dependency: 's'
    }, {
        id: 'a',
        name: 'Run acceptance tests',
        start: Date.UTC(2014, 10, 23),
        end: Date.UTC(2014, 10, 26)
    }, {
        name: 'Test prototype',
        start: Date.UTC(2014, 10, 27),
        end: Date.UTC(2014, 10, 29),
        dependency: ['a', 'b']
        }]
    }]
});


  })

In essence, it appears that AngularJS executes first, causing the highcharts script not to be loaded before setting up the highcharts gantt chart as intended. I appreciate any assistance provided. My knowledge of frontend/javascript development is limited, and I welcome the chance to expand my skills.

Answer №1

In the example you provided, I noticed that:

  1. You didn't include the angularjs script.
  2. You didn't write the ng-app directive.

For a fully functional example, you can refer to this link.

Although the example uses different types of charts, the underlying principles remain the same:

<!DOCTYPE html>
<html ng-app="myModule">
<head>
    <meta charset="utf-8" />
    <title> Highcharts directive demo </title>
    <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.5/angular.min.js"></script>
    <script type="text/javascript" src="https://code.highcharts.com/highcharts.js"></script>
</head>
<body ng-controller="myController">

     <hc-chart options="chartOptions">Placeholder for generic chart</hc-chart>
     <hc-pie-chart title="Browser usage" data="pieData">Placeholder for pie chart</hc-pie-chart>

    <script>
        angular.module('myModule', [])
            // Directive for generic chart, pass in chart options
            .directive('hcChart', function () {
                return {
                    restrict: 'E',
                    template: '<div></div>',
                    scope: {
                        options: '='
                    },
                    link: function (scope, element) {
                        Highcharts.chart(element[0], scope.options);
                    }
                };
            })
            // Directive for pie charts, pass in title and data only    
            .directive('hcPieChart', function () {
                return {
                    restrict: 'E',
                    template: '<div></div>',
                    scope: {
                        title: '@',
                        data: '='
                    },
                    link: function (scope, element) {
                        Highcharts.chart(element[0], {
                            chart: {
                                type: 'pie'
                            },
                            title: {
                                text: scope.title
                            },
                            plotOptions: {
                                pie: {
                                    allowPointSelect: true,
                                    cursor: 'pointer',
                                    dataLabels: {
                                        enabled: true,
                                        format: '<b>{point.name}</b>: {point.percentage:.1f} %'
                                    }
                                }
                            },
                            series: [{
                                data: scope.data
                            }]
                        });
                    }
                };
            })
            .controller('myController', function ($scope) {

                // Sample options for first chart
                $scope.chartOptions = {
                    title: {
                        text: 'Temperature data'
                    },
                    xAxis: {
                        categories: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 
                            'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']
                    },

                    series: [{
                        data: [29.9, 71.5, 106.4, 129.2, 144.0, 176.0, 135.6, 148.5, 216.4, 194.1, 95.
                         6, 54.4]
                    }]
                };

                // Sample data for pie chart
                $scope.pieData = [{
                        name: "Microsoft Internet Explorer",
                        y: 56.33
                    }, {
                        name: "Chrome",
                        y: 24.03,
                        sliced: true,
                        selected: true
                    }, {
                        name: "Firefox",
                        y: 10.38
                    }, {
                        name: "Safari",
                        y: 4.77
                    }, {
                        name: "Opera",
                        y: 0.91
                    }, {
                        name: "Proprietary or Undetectable",
                        y: 0.2
                }]
            });
    </script>
</body>
</html>

If you simply copy and paste the code above into an HTML file, you will see the output shown here: https://i.sstatic.net/wBwZn.png.

It is advisable to separate each directive into its own code (including the directive's markup).

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

Vue.js global event issue

Recently, I encountered an issue with the following code: <component-one></component-one> <component-two></component-two> <component-three></component-three> Specifically, component-two contains component-three. My cu ...

Error message: Incorrect XMP data detected within PhotoSphereViewer" and "WebGL issue: INVALID_VALUE error when attempting to load faulty image data

I'm currently utilizing Photo Sphere Viewer to showcase a panoramic image similar to how Facebook does it, but I am encountering some difficulties. Below is the code snippet: <script src="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/em ...

When encountering issues with the select element, such as when it is combined with AJAX or Bootstrap,

When attempting to use a foreach loop within the <select><option> ... </option></select> element with jquery + ajax, I encountered an issue where no values were displayed. Although there were no errors when reviewing the console lo ...

Instructions for creating a cutout on a doughnut chart using ng2-charts

Can someone help me with setting configuration options on my doughnut chart using ng2-charts? Specifically, I am trying to set the cutout property on the chart. Despite going through the documentation for charts-js and ng2-charts, I haven't been able ...

Placing content retrieved from a MySQL database within a form displayed in a ColorBox

Having difficulty inserting text from a MySQL database into a form (textfield) inside a ColorBox. The current script is as follows: <a href="#" class="bttn sgreen quote1">Quote</a> var postQuote[<?php echo 4id; ?>]=<?php echo $f ...

Implementing a scrolling text feature in React

I have a unique requirement for my text to be displayed once I am 100px above it, and to remain hidden before reaching that point. Additionally, I want the text to slide in from the left once it hits that 100px mark. This is a new challenge for me, as I ha ...

Is it possible to retrieve resolved parameters from a template-rendering function?

I'm facing a scenario where I have a state setup like this .state('dropdown', { url: '/dropdown', views: { "@":{ template: ...

Updating view with *ngIf won't reflect change in property caused by route change

My custom select bar has a feature where products-header__select expands the list when clicked. To achieve this, I created the property expanded to track its current state. Using *ngIf, I toggle its visibility. The functionality works as expected when cli ...

Exploring the functionality of uiRouter using the requirejs framework

I've been struggling with a problem for a while now and haven't found any solutions in other posts related to testing uiRouter with requirejs. I have a basic controller set up that uses $state.go to switch states when a button is clicked. runsCo ...

What is the best way to shorten a tweet that goes over 140 characters?

I have an algorithm for tweeting that eliminates @-mentions and will not post tweets under the following conditions: 1) if the question is different from the answer, 2) if the composed tweet exceeds 140 characters, and 3) if the tweet is potentially sensit ...

Module Not Found Error: Electron and Typescript Collaboration

I am currently facing an issue while attempting to build my electron application using typescript generated from the electron-quick-start-typescript project. I have included an additional module named auth.ts, but unfortunately, it is not being recognized ...

Discover the process of accessing and setting values in Angular 8 to easily retrieve and manipulate data from any page!

Greetings! I am currently utilizing Angular 8 and I have a query regarding how to access the set value in any given page. Here is a snippet of my code: class.ts export class testClass { get test():string{ return this.sexe; } ...

I have been attempting to implement validation in JQuery, but it doesn't seem to be functioning correctly

Can someone assist me with adding validation in jQuery? I'm stuck and need help solving this problem. $(function(){ $("#btn").click(function(){ var b=prompt("Enter your link"); $("a").attr("href",b); if($("b").v ...

JSFiddle Functioning Properly, But Documents Are Not Loading

My JSFiddle is functioning properly, but the files on my computer aren't. It seems like there might be an issue with how they are linking up or something that I may have overlooked. I've checked the console for errors, but nothing is popping up. ...

Connecting the v-model in a Vue.js child component to update the parent value

I've encountered an issue with a vue component where I'm trying to link a text input in the child template to a variable in the parent using v-model, but it doesn't seem to be working. How can I make this work? Currently, I am using Vue.js ...

Is there a universal resolver available for the $routeProvider in AngularJs 1.x?

Can a service be globally resolved for all routes in AngularJs? For example, if I need to retrieve configuration from a Web Service for all the routes, is it possible to achieve something similar to the following pseudocode? $routeProvider .when(&apos ...

Steps to dynamically populate a datatable with JSON data by triggering a click event in jQuery

I am facing an issue with feeding JSON data into datatables when the search button is clicked. The JSON data structure is as follows: [ { "port_code":"BOM", "cont_details_id":"9", "price":"44.000", "cont_price":"500", "c ...

The challenge of populating information within a Datalist

In my code snippet, I have a JavaScript function that is used to populate a Datalist: function PopulateDropDown(facility) { $.ajax({ url: '/Rentals/Base/GetContactsForFacility?selectedFacility=' + facility, data: { facility: ...

The concept of undefined functions and the use of dependency injection may not always align

Recently starting with AngularJs, I am honing my skills by developing a single page Todo Application. However, I have encountered an issue while trying to load a localStorage factory that I intend to use for this project. Currently, I am stuck on the error ...

Retrieve Javascript files from the local static directory

Currently, I am developing a small project with Nuxt JS and I am facing a challenge in calling some Javascript files from my static directory. When it comes to CSS files, I have been able to do it successfully using the following code: css: [ './stat ...