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

Efficiently processing multiple Ajax requests with a single callback function

I am currently facing a situation where I need to make multiple AJAX requests and only proceed if all of them are successful. The typical usage of $.when($.ajax(), [...]).then(function(results){},[...]); doesn't quite fit my needs because the number o ...

JavaScript ACTING UP -> CROSS-ORIGIN RESOURCE ACCESS ERROR

After extensive research and troubleshooting, it dawned on me that the issue was not with JavaScript itself. Instead, I was facing a cross origin resource exception, which occurred because the ajax request was unable to access my server script due to lac ...

`Zooming and scrolling feature within a masked image`

I'm struggling to achieve a scrolling zoom effect similar to the website mentioned below, but I can't seem to get it to fully zoom. Additionally, when I try to zoom in on a clipped shape or text while scrolling, the entire div ends up scrolling ...

Utilize Symfony filtering alongside AJAX functionality with the added feature of the KnpPaginatorBundle

When filtering data using ajax, I encounter an issue with pagination in Symfony and KnpPaginatorBundle. The pagination works fine when displaying the data without any filters. However, after applying a filter using ajax, clicking on page 2 of the paginati ...

Why is my AngularJS application triggering two events with a single click?

<button id="voterListSearchButton" class="serachButton" ng-click="onSearchButton1Click()">find</button> This button allows users to search for specific information: $scope.onSearchButton1Click = function() { var partId = $("#partIdSearch" ...

Tips on transferring information from Angular to Rails

I am quite new to Angular, having only started learning it a week ago. My query pertains to how data can be transferred from Angular to Rails. Essentially, I wish to store whatever is input into {{entry.name}} in Rails. Appreciate your assistance! & ...

Having Trouble Parsing JSON Object with JQuery?

I'm having trouble extracting data from a valid JSON object using jQuery/JavaScript - it always returns as 'undefined'. var json = (the string below). var obj = $.parseJSON(JSON.stringify(JSON.stringify(json))); alert(obj); // aler ...

Is it possible to make a link_to, which is essentially a normal <a href>, clickable through a div that is also clickable?

I am currently dealing with a clickable div element which has a collapse functionality, and there is also a link placed on top of it: <div class="panel-group" id="accordion"> <div class="panel panel-default"> <div class="panel-h ...

Discover the secrets of flying to customized coordinates stored in variables using Leaflet.js

I'm currently working on a fire location tracking website and I'm facing an issue with leaflet.js. As a newcomer to Leaflet, any assistance would be greatly appreciated! I have a script that successfully retrieves the id of a specific row from a ...

Having trouble getting a NodeJS sample app to start up because it can't locate the 'config' file?

I am currently delving into the world of Node.js and have been attempting to launch a sample application that I recently acquired from a git repository: https://github.com/madhums/node-express-mongoose-demo Despite diligently following all the provided i ...

Tips for concealing the values within a selected dropdown list using jQuery

Hello, I'm currently working on a jQuery application that involves a dropdown list box and a gridview. The first column of the gridview has checkboxes with a check all button at the top. My goal is to disable corresponding values in the dropdown list ...

How can I verify if a user is logged in using express.Router middleware?

Is there a way to incorporate the isLoggedIn function as a condition in a get request using router.route? const controller = require('./controller'); const Router = require('express').Router; const router = new Router(); function isLo ...

The anchor tag fails to trigger the onClick function in React

I'm having trouble updating the component state in my React app when clicking on an anchor tag within the render method. I've attempted to bind the function in the constructor, but the console.log statement is still not being called. Here's ...

Connect the scroll wheel and then proceed to scroll in the usual way

There are two div elements with a height and width of 100%. One has the CSS property top:0px, while the other has top 100%. I have implemented an animation that triggers when the mousewheel is used to scroll from one div to the other. The animation functi ...

Using JavaScript to transform base64 encoded strings into images

I'm currently working on an app using Titanium and I have a base64 string that I need to convert into an image from JSON data. Any assistance you can provide would be much appreciated. Thank you! ...

Activate the parent navigation link when on sub-pages

I want to ensure that the parent navigation item is highlighted when a user is on a child page based on the URL. For example, if the user is currently viewing foo1-child and the parent is foo1, I need to apply the active class to Foo 1: http://foo.com/foo ...

Leveraging split and map functions within JSX code

const array = ['name', 'contact number'] const Application = () => ( <div style={styles}> Unable to display Add name & contact, encountering issues with splitting the array). </div> ); I'm facing difficul ...

Looking for a solution to eliminate Parsing Error: Unexpected Token when developing with React? I've already implemented ESLint and Prettier

Currently, I am working on building a form in React with MUI. Below is the code snippet that I have been working with: const textFields = [ { label: 'Name', placeholder: 'Enter a company name', }, { label: 'Addres ...

Issue with hashtag in regular expressions

Looking for a way to identify and link hashtag words with an anchor tag? Here's a snippet showcasing the concept: <p class="display"></p> var content = "I enjoy #blueSky. My favorite color is #green. #sky is amazing"; ...

Retrieving the latest entry from the MySQL database

I am encountering an issue with a code that involves fetching data from MySQL into an array. I have a form with color and size select boxes, and when an onclick javascript function is triggered it creates two additional select boxes. I have successfully re ...