Can an array in html be accessed using a scope variable?

I am facing a challenge with utilizing a Json array in my template file. To access specific elements of the array, I need to use a scope variable. While I can achieve this in the controller, I also require the same functionality in the HTML file.

An excerpt from my array is provided below:

{
fitbit: {
    selected: true,
    user_id: "10537",
    today: [
        {
            date: "Tue, 10 Jan 2017",
            distance: 0,
            steps: 0,
            calories: "0"
        }
    ],
    week: {
        distance: [
            ["0","0","0","0","0"]
        ],
        labels: ["Wed 4th","Thu 5th","Fri 6th","Sat 7th","Sun 8th"],
        steps: [
            ["0","0","0","0","0"]
        ]
    }
},
jawbone: { ... }
}

In my scenario, I have a scope variable $scope.currentDevice that changes based on the user's selection (e.g., fitbit, jawbone). In the controller, I can retrieve the correct data using

$scope.wearables[currentDevice]['week']['distance']
, where 'currentDevice' dictates which data to access.

The challenge lies in accessing

wearables[currentDevice]['week']['distance']
directly in the template HTML file without employing ng-repeat and leveraging the 'currentDevice' scope variable to determine which data to display.

When attempting

{{wearables[currentDevice]['week']['distance']}}
in the HTML file, it does not render any value. However, using
{{wearables['fitbit']['week']['distance']}}
displays the expected value.

Is there a way to achieve this approach for displaying array data, and if so, how can it be implemented?

The desired format for showcasing the array data is to visualize it in a graph as depicted below:
where chart-data changes

<canvas id="bar" class="chart chart-bar" chart-data="wearables[currentDevice]['week']['distance']" chart-labels="labels" chart-series="series" chart-options="options" ></canvas>

If switching to

<canvas id="bar" class="chart chart-bar" chart-data="wearables['fitbit']['week']['distance']" chart-labels="labels" chart-series="series" chart-options="options" ></canvas> 

this arrangement functions as intended.

Answer №1

In order to accurately display the data in the graph, a specific function was utilized. Rather than attempting to showcase information using

wearables[currentDevice]['week']['distance']
, the decision was made to employ getDistance(currentDevice) to retrieve the precise data.

The code for the graph now appears as follows:

<canvas id="bar" class="chart chart-bar" chart-data="getDistance(currentDevice)" chart-labels="labels" chart-series="series" chart-options="options" ></canvas>

Within the controller, the getDistance(device) method is responsible for modifying the data based on the value of $scope.currentDevice:

$scope.getDistance = function(device) {
    console.log('current device', device );
    return $scope.wearables[device]['week']['distance'];
}

Answer №2

If your chart is not displaying correctly, it is possible that the chart-data attribute is not being evaluated properly due to a potential issue driving the chart. You can try resolving this by changing chart-data to ng-attr-chart-data and observing if the chart renders as expected:

<canvas id="bar" class="chart chart-bar" ng-attr-chart-data="wearables[currentDevice]['week']['distance']" chart-labels="labels" chart-series="series" chart-options="options" ></canvas>

To learn more about ngAttr, you can refer to: https://docs.angularjs.org/guide/interpolation

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

Changing Text in React Native is Customizable

As a newcomer to react native, I find myself in need of some guidance. I am currently working on implementing a TextInput feature where users can update the text value as they please. For instance, if a user initially creates a folder named "Bar" but later ...

Stop the form from submitting when the Enter key is pressed

I am experiencing an issue with my form that contains around 10 input text boxes. When I press the enter key from an input text box, it skips the text boxes in between and goes directly to the submit button. This problem occurs only when using the keyboard ...

Proper syntax for SVG props in JSX

I have developed a small React component that primarily consists of an SVG being returned. My goal is to pass a fill color to the React component and have the SVG use this color. When calling the SVG component, I do so like this: <Icon fillColour="#f ...

Maximizing performance: optimizing Javascript usage in .net Web Application

After completing a web application using C#, ASP, and some javascript, my main page is cluttered with a mix of javascript/jQuery at the bottom. I have several ajax calls to web methods in this mess. Is there a way to organize this javascript into multipl ...

Using a URL in an AJAX request

Before redirecting to another page, I am storing data from a textbox. When the user clicks the back button on the page load function in JavaScript, I retrieve the data from the textbox using: var pageval = $('#grid') .load('/Dealer/AllClai ...

Refreshing Angular Page

I'm looking for a way to reset my Angular page back to its original state with just one button click. I attempted to use the angular.copy method, but encountered an error. I have various scope and controller variables that I don't want to reset i ...

Error encountered: Jquery counter plugin Uncaught TypeError

I am attempting to incorporate the JQuery Counter Plugin into my project, but I keep encountering an error: dashboard:694 Uncaught TypeError: $(...).counterUp is not a function <!DOCTYPE html> <html lang="en"> <head> <script src ...

Choose or deselect images from a selection

I am currently working on a feature for an album creation tool where users can select photos from a pool of images and assign them to a specific folder. However, I'm facing difficulty in selecting individual photos and applying customized attributes t ...

How can I use jQuery to pre-select an option in two connected dropdown lists that are populated with JSON data?

I am currently dealing with two interconnected dropdown lists for country and city selection. The options are populated using JSON data, but I've encountered a couple of issues along the way. The first issue is: How can I set the default selected opti ...

Switching on click using jQuery

I'm having some difficulties with my code and I can't quite figure out how to solve the problem at hand. To be honest, I'm not even sure what the exact question is here. If it seems a bit confusing, I apologize - I'm still new to Jquery ...

Incorporate Angular exclusively in pages that are dynamically loaded via ajax requests

<html> <head> <title></title> <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.7/angular.js"></script> </head> <body> <div id="ajax-content-here"> </div> </body> ...

Is there a way to display the back and forward buttons on a popup window opened through window.open or self.open in Chrome browser?

When I try to open a popup window using the code snippet below, I am facing some issues. self.open('myJSPPage','ServicePopUp','height=600,width=800,resizable=yes,scrollbars=yes,toolbar=yes,menubar=yes,location=yes'); Afte ...

"Encountering a Heroku error due to an oversized cookie while using Express.js and

Being unsure of the exact cause, I am encountering an issue with Heroku that gives me the error message t=error code=H25 desc="HTTP restriction: oversized cookie" whenever I attempt to authenticate myself with Discord OAuth. Interestingly, this problem onl ...

Executing Basic Authentication in Javascript through window.open()

After a user logs into my app, they have the option to download a CSV file from the server by clicking on a button. The URL for the download is secured with basic authentication. When attempting to open the URL using the code below: window.open('http ...

Do not allow nested objects to be returned

I am facing an issue with typeorm, where I have a queryBuilder set up like this: const projects = await this.conn.getRepository(UserProjectRelations).createQueryBuilder("userProject") .innerJoin("userProject.userId", ...

Updating the JSON data with a new row

I am trying to dynamically add a new row to my JSON data when the user clicks on a link. Despite not receiving any errors, I am unable to see the updated JSON in my alert message. $(document).ready( function(){ people = { "COLUMNS":["NAME","AGE"], ...

What could be the reason for the email not being displayed in the form?

I am attempting to automatically populate the user's email in a form when a button is clicked, preferably when the page is loaded. However, I am encountering issues with this process. This project is being developed using Google Apps Script. Code.gs ...

Revamp your arrays with input fields in Vue3

When presented with two arrays of options, users must select an option from each array. ==> first array: [ orange, green, yellow ] ==> second array: [ orange, green, yellow ] The challenge is to update the second array based on the user's sele ...

Oops! Looks like there was an error: weight is not defined when trying to calculate BMI with the HTMLButtonElement

I'm currently working on a project to create a BMI calculator following specific instructions. I've managed to follow all the guidelines except one regarding the letsCalculateBMI function. The instruction states: letsCalculateBMI should extrac ...

Is it possible to iterate over a non-reactive array in a Vue template without having to store it in a data property or computed property?

Presented below is a static array data: const colors = ["Red", "Blue", "Green"]; To display these values in my markup, I can use the following method in React: import React from "react"; // Static array of colors const colors = ["Red", "Blue", "Green"] ...