How to retrieve scope variable within the <script> element

I have a question about using angularjs.

Here is the structure of my HTML:

<html>
    <body ng-controller="datafileController">
        <div class="container">
            <center><h1>Datafiles</h1></center>
            <div class="row" ng-repeat="i in datafile.items">
                <div class="col-sm-8">
                    <p>Total MB: {{i.total_mb}}</p>
                    <p>Used MB: {{i.used_mb}}</p>
                    <p>Free MB: {{i.free_mb}}</p>
                    <br>
                    <br>
                </div>
                <div class="col-sm-4">
                    <div id="myDiv"></div>
                    <script>
                        var data = [{
                            values: [{{i.used_mb}}, {{i.free_mb}}],
                        labels: ['Free MB', 'Used MB'],
                            type: 'pie'
                        }];
                        Plotly.newPlot('myDiv', data);
                    </script>
                </div>
            </div>
        </div>
    </body>
</html>

And this is how my controller looks like:

aebdApp.controller('datafileController', function($scope, $http) {
    $http.get('http://127.0.0.1:8083/json/datafiles.json').
     then(function(response) {
        $scope.datafile = response.data;
    }); 
});

Can someone guide me on how to access the i variable in the data section? I want to create a graph using Plotly for each item. Thank you.

Answer №1

This is the method I employ to achieve this:

<html>
<body ng-controller="datafileController">
<div class="container">
    <center><h1>Datafiles</h1></center>
    <div class="row" ng-repeat="i in datafile.items">
        <div class="col-sm-8">
            <p>Total MB: {{i.total_mb}}</p>
            <p>Used MB: {{i.used_mb}}</p>
            <p>Free MB: {{i.free_mb}}</p>
            <br>
            <br>
        </div>
        <div class="col-sm-4">
            <div id="myDiv_{{$index}}"></div>
        </div>
    </div>
</div>

<script>
    aebdApp.controller('datafileController', function ($scope, $http, $timeout) {
        $http.get('http://127.0.0.1:8083/json/datafiles.json').then(function (response) {
            $scope.datafile = response.data;

            $timeout(function () {
                $scope.datafile.forEach(function (i, index) {
                    var data = [{
                        values: [i.used_mb, i.free_mb],
                        labels: ['Free MB', 'Used MB'],
                        type: 'pie'
                    }];

                    Plotly.newPlot('myDiv_' + index, data);
                });
            }, 1000);
        });
    });
</script>
</body>
</html>

Essentially, utilizing the innate $index variable and integrating the $timeout function. The necessity of the $timeout function remains uncertain.

Answer №2

Avoid placing code that manipulates the DOM within controllers. Instead, consider creating a specialized directive:

app.directive("plotly", function() {
    return {
        link: postLink
    };
    function postLink(scope,elem,attrs) {
        scope.$watch(attrs.plotly, function(i) {
            if (i) {
                 var data = [{
                     values: [{{i.used_mb}}, {{i.free_mb}}],
                     labels: ['Free MB', 'Used MB'],
                     type: 'pie'
                 }];
                 Plotly.newPlot(elem[0], data)
            };
        });
    }
}

HOW TO USE:

<div class="row" ng-repeat="i in datafile.items">
    <div class="col-sm-8">
        <p>Total MB: {{i.total_mb}}</p>
        <p>Used MB: {{i.used_mb}}</p>
        <p>Free MB: {{i.free_mb}}</p>
        <br>
        <br>
    </div>
    <div class="col-sm-4">
        <div id="myDiv{{$index}}" plotly="i"></div>
    </div>
</div>

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

Aggregate the values in an array and organize them into an object based on their frequency

I have an array of information structured like this: 0: { first: "sea", second: "deniz", languageId: "English-Turkish"} 1: { first: "play", second: "oynamak", languageId: "English-Turkish&qu ...

Conflicts in routing between Node.js and AngularJS

Currently, my setup involves NodeJS, gulp, and Angular with ui-router. However, I have encountered an issue when configuring Angular to remove the tag (#) from the routes. The problem arises as Angular's routes do not seem to work properly, and the na ...

Update a single javascript variable on every rotation of the Bootstrap carousel

Within my website, I have implemented a popin/modal feature using Hubspot Messenger which includes a Bootstrap 3 carousel. Each slide of the carousel displays a different "social embed" such as Facebook or Twitter, and I am looking to adjust the width of t ...

When JSON contains slashes, JSON.parse will trigger an error

I am struggling with a valid JSON generated using PHP like this: var json = <?php echo json_encode(['somearray']); ?>. Inside the array, there is an HTML string as shown below: $myArray = ['image' => '<img src="/img/f ...

Transforming an older React website with react-helmet-async

I am working on a React site that is client-side rendered and I want to use the react-helmet-async module (version 1.0.7). Here's my scenario in the React app: /public/index.js: <head> <title>My title in the index file</title> ...

Attempting to retrieve key-value pairs from a nested JSON array

I am attempting to extract values along with their corresponding key names from a nested JSON array resData =[ { _index: 'web', _type: 'event', _id: 'web+0+93', _score: null, _source: { 'os-nam ...

Can you explain the purpose and functionality of the 'next' parameter within a middleware function in the Node.js Express framework?

Currently, I am working on Nodejs with the use of "Express js". My focus is on the implementation of "middleware functions," and here is a snippet of my existing code: const express = require('express') const app = express() ...

Passport JS allows you to create a secure login form that redirects users to different URIs based on their role

Currently, I am utilizing Passport JS for authentication management and Express JS to handle routing within my application. At the moment, I have a login route that directs to the /teacher URI upon successful authentication (as depicted below). app.post( ...

Navigating through objects within arrays within objects in Angular

I seem to be encountering some difficulty in displaying data from an API call on Mapbox. Only one marker is showing up on the map instead of the expected 10 markers. I suspect there might be an issue with my ng-repeat implementation, but I can't pinpo ...

Vue component fails to render due to a simple issue

I've been diving into Vue.JS and I'm facing an issue where the component I created isn't showing up on the page. Here's a snippet of my component: import Vue from 'vue' const card = new Vue({ el: '#card', data: ...

Making sure the checkbox stays selected in an angular environment

After experimenting with Angular 9 and a custom input, I achieved the following result => https://stackblitz.com/edit/angular-ivy-rgsatp My goal was to prevent users from disabling a radio button that is currently checked. Therefore, I made changes in ...

Utilize Page.evaluate() to send multiple arguments

I am facing an issue with the Playwright-TS code below. I need to pass the email id dynamically to the tester method and have it inside page.evaluate, but using email:emailId in the code throws an undefined error. apiData = { name: faker.name.firstNa ...

Adding an additional parameter in the ListItem onMouseOver function

Within my React code base, I have a material-ui ListItem that looks like this: <ListItem button key={currIndex} onMouseOver={handleOnMouseClickOnListItem}> The handler function in my code (using Flow typing) is as follows: const handleOnMouseClic ...

At times, an InvalidArgumentError occurs stating: "The 'handle' parameter must be a string."

I have incorporated 'React-google-login' into my React project and now I am working on an automated test to make sure it functions correctly. try { await driver.get("http://localhost:3000/"); await driver.wait(until.elementLocated(By.xpath(` ...

Retrieving a variable in a JavaScript function while a webpage is in the process of loading

Recently, I was working on writing Selenium test cases in C# and encountered an issue while trying to capture a value from a webpage. The problem arose when the retrieved value was rounded to 5 decimal points which was not what I wanted. Instead, I needed ...

Can a variable declared in wdio.conf be accessed?

Within the wdio.conf file, I have implemented a function called onPrepare where I am storing all my feature files in an array. let listOfFiles = fs.readdirSync(process.cwd() + '/features'); var featureFiles = []; listOfFiles.map((file) => { ...

Removing information from a MongoDB database with the help of AngularJS and Node.js

Having trouble deleting data in MongoDB using AngularJS and Node.js, as I keep encountering the error "Cannot DELETE /api/manage-product" in the console. .html file <tbody> <tr ng-repeat="product in vm.result"> ...

What does the underscore before a function in JavaScript or PHP signify?

I am curious about the significance of the underscore symbol (_) when it is placed before a function or variable. Does it serve to simply describe something, or is it required for executing specific functions or calling certain methods? In JavaScript: va ...

Events in the cell header of Angular ui-grid are not triggering as expected

Currently, I am implementing a headerCellTemplate within the columDefs of my ui-grid (not ng-grid but the newly updated version). Within the HTML code, I have inserted a checkbox. My goal is to include a checkbox in the column header where all checkboxes a ...

Automatically update div content using jQuery including an AJAX request for loading

I have successfully implemented a method for loading output from now_playing.php (shoutcast now playing content) using a jQuery include ajax call, as recommended in this answer on Stack Overflow. Here is my code: <script> $(function(){ $("#now_ ...