Loop through different JSON objects with unique values using ng-repeat

I am facing an issue with a JSON file that contains three different objects for each area, and I need some help. Here is an example:

{
    "gebieden":"Antwerpen",
    "onderwerpen":"Gemiddeld netto inkomen per belastingsplichtige",
    "data_2005":"15084,8252887",
    ...
},
{
    "gebieden":"Antwerpen",
    "onderwerpen":"Mediaan netto inkomen",
    "data_2005":"11424",
    ...
},
{
    "gebieden":"Antwerpen",
    "onderwerpen":"Aantal belastingsplichtigen",
    "data_2005":"129568",
    ...
}

The challenge is to display all areas in an accordion group where the property "gebieden" has the same value. I have managed to achieve this layout using AngularJS:

<div class="panel-group" id="accordion">
    <div class="panel panel-default" ng-repeat="item in All | unique:'gebieden'">
        <div class="panel-heading text-center" data-toggle="collapse" data-parent="#accordion" id="{{item.gebieden}}" href="#{{$index}}">
            <h4 class="panel-title">
                {{item.gebieden}}
            </h4>
        </div>
        <div id="{{$index}}" class="panel-collapse collapse ">
            <div class="panel-body text-center">
                <ul class="nav nav-tabs">
                    <li ng-repeat="item in All | unique:'onderwerpen'">
                        <a data-toggle="tab" href="#{{item.onderwerpen}}">
                            {{item.onderwerpen}}
                        </a>
                    </li>
                </ul>
                <div class="tab-content" style="padding:2%">
                    <div id="{{item.onderwerpen}}" class="tab-pane fade in active">
                        <table class="table table-bordered text-center">
                            <thead>
                                <tr>
                                    <th class="text-center">Jaar</th>
                                    <th class="text-center">Waarde</th>
                                </tr>
                            </thead>
                            <tbody>
                                <tr ng-repeat="(key,val) in item | comparator" ng-hide="$index<2" >
                                    <td>{{key}}</td>
                                    <td>{{val}}</td>
                                </tr>
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

I have implemented a tab layout for the panel body, creating tabs based on the values of "onderwerpen" from the JSON. However, I'm struggling to access the data from the object with a specific "onderwerpen" value as I am using the unique filter to avoid duplicate data. How can I make only the data from the selected tab show?

If my question is unclear, please let me know so I can provide more information. Thank you.

Answer №1

To sort out the object based on the tab that was clicked, you can utilize the filter function. I have provided a functional fiddle below which showcases the properties according to the selected tab - http://jsfiddle.net/uwpjk28w/12/

In essence, I included an ng-click function that alters the onderwerpen property:

<a data-toggle="tab" ng-click="setOnderwerpen(item.onderwerpen)">
     {{item.onderwerpen}}
</a>

The function responsible for modifying the onderwerpen is as follows:

 $scope.selectedOnderwerpen = '';
 $scope.setOnderwerpen = function (onderwerpen) {
        $scope.selectedOnderwerpen = onderwerpen;
 }

Additionally, the filter implementation is detailed below:

<tbody ng-repeat="item in All | filter {onderwerpen:selectedOnderwerpen}:true">
      <tr ng-repeat="(key,value) in item" ng-show="$index < 7">
           <td>{{key}}</td>
           <td>{{value}}</td>
      </tr>
</tbody>

Moreover, by using ng-show, the table will only be displayed once a tab has been selected.

ng-show="selectedOnderwerpen!=''" 

I trust this information proves beneficial.

Answer №2

In my opinion, a more effective way to structure the JSON data would be like this:

{
   "areas":"Antwerp",
   "topics":"Average net income per taxpayer",
   "data":{
      "data_2005":"15084,8252887",
      "data_2006":"14935,2782929",
      "data_2007":"15353,0192747",
      "data_2008":"16040,981705",
      "data_2009":"16050,4881554",
      "data_2010":"15777,0232385",
      "data_2011":"16487,8501985"
   }
},
{
   "areas":"Antwerp",
   "topics":"Median net income",
   "data":{
      "data_2005":"11424",
      "data_2006":"11194",
      "data_2007":"11445",
      "data_2008":"12208",
      "data_2009":"12316",
      "data_2010":"12211",
      "data_2011":"12788"
   }
},
{
   "areas":"Antwerp",
   "topics":"Number of taxpayers",
   "data":{
      "data_2005":"129568",
      "data_2006":"137614",
      "data_2007":"141273",
      "data_2008":"142771",
      "data_2009":"146058",
      "data_2010":"151516",
      "data_2011":"151674"
   }
}

To access the data efficiently, you can utilize the following HTML structure:

<!DOCTYPE html>
<html ng-app="app">

  <head>
    <link rel="stylesheet" href="style.css">
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.5/angular.min.js"></script>
    <script src="script.js"></script>
  </head>

  <body >
    <div class="panel-group" id="accordion" ng-controller="mainCtrl">
                    <div class="panel panel-default" ng-repeat="item in All">
                        <div class="panel-heading text-center" data-toggle="collapse" data-parent="#accordion" id="{{item.areas}}" href="#{{$index}}">
                            <h4 class="panel-title">
                                {{item.areas}}
                            </h4>
                        </div>
                        <div id="{{$index}}" class="panel-collapse collapse ">
                            <div class="panel-body text-center">
                                <ul class="nav nav-tabs">
                                    <li>
                                        <a data-toggle="tab" href="#{{item.topics}}">
                                            {{item.topics}}
                                        </a>
                                    </li>
                                </ul>
                                <div class="tab-content" style="padding:2%">
                                    <div id="{{item.topics}}" class="tab-pane fade in active">
                                        <table class="table table-bordered text-center">
                                            <thead>
                                                <tr>
                                                    <th class="text-center">Year</th>
                                                    <th class="text-center">Value</th>
                                                </tr>
                                            </thead>
                                            <tbody>
                                                <tr ng-repeat="(key,val) in item.data" ng-hide="$index<2" >
                                                    <td>{{key}}</td>
                                                    <td>{{val}}</td>
                                                </tr>
                                            </tbody>
                                        </table>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>

  </body>

</html>

For a live demonstration, visit this plunker link.

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

Troubleshooting: JavaScript Bookmarklet Fails to Execute on Certain Websites

Recently, I created a unique bookmarklet that functions flawlessly on some websites, but unfortunately fails to work on others. Interestingly, even when it doesn't work, the script is still added to the bottom of the page; however, only a portion of t ...

Error in JSON mapping dictionary

After reading my JSON file and setting a string variable using System.Web.Script.Serialization, I encountered an error when trying to deserialize the data. FileStream fs = new FileStream(Server.MapPath("odul_en.json"),FileMode.Open,FileAccess.Read); ...

python: understanding the behavior of json.dumps with dictionaries

My goal is to modify the behavior of the dict when using json.dumps. I want to be able to order the keys, so I created a new class that inherits from dict and overrides some of its methods. import json class A(dict): def __iter__(self): for i ...

What is the best method for inserting a solo marker into a Google Maps v3?

Below is the code where I am currently displaying the greyscale of a map using Google Maps v3 based on latitude and longitude values retrieved from a database. I need assistance in placing only one marker at the specified latitude and longitude coordinat ...

Is Valums Ajax file Upload capable of handling the uploaded file?

Currently, I am utilizing the Valums Ajax Fileupload script found at These are the settings I have configured: function createUploader(){ var uploader = new qq.FileUploader({ element: document.getElementById('file-uploader-de ...

What is the procedure for inserting multiple rows into a MySQL database using JSON data from an Android

I am facing a challenge with inserting multiple rows into a MySQL database from Android. Currently, I only know how to insert one row. Here is the PHP script snippet: $r=mysql_query($sql); if(!$r) echo "Error in query: ".mysql_error(); mysql_close(); ...

Retrieving the response value in AngularJS with $resource

I'm trying to retrieve the response of a request using $resource in AngularJS. Here is an example implementation: angular.module('app').factory('AuthResource', ['$resource', function($resource) { return { isA ...

Converting JSON objects into datetime: A step-by-step guide

I am looking for a way to display JSON data in a Kendo chart. Below is the code I have: <head> <meta charset="utf-8"/> <title>Kendo UI Snippet</title> <link rel="stylesheet" href="https://kendo.cdn.telerik.com/2019 ...

My selection of jQuery multiselect is experiencing issues with enabling disabled options

Incorporating the chosen jQuery plugin into my project has presented me with a challenge. The issue at hand is listed below. I have implemented a dropdown menu that includes both continents and countries in the same list. The specific scenario I am encou ...

Displaying a Google chart with no data using JSON

Recently, I've been tackling the challenge of setting up Google Charts to display data from a local database. After some persistence, I believe I have successfully formatted the JSON output. { "cols": [ { "id": "", ...

Is there a way to modify the appearance of blocks in Scratch/Blockly?

I am currently working on customizing the appearance of the blocks in Scratch by looking into adjusting the GitHub repository of scratch-blocks (https://github.com/LLK/scratch-blocks). There is a chance that I might need to modify the GitHub repository of ...

Can a condition be incorporated in a gulpfile to execute a task depending on the size of a file?

Currently, I am utilizing gulp for image compression. However, my requirement is to only compress images exceeding 200kb in size. Can JavaScript be used to loop through a directory and selectively run the minification process on files larger than 200kb? ...

Ways to extract a single digit from the total sum of a date in the format of 15-06-2015

Is there a way to extract a single digit from the sum of a number in date format, such as 15-06-2015? My goal is to convert the date format 15-06-2015 into a single-digit value by adding up the numbers. For instance: In the case of 15-05-2015, the output ...

Angular routes do not populate the $state in resolving promises

Recently, I encountered a situation where $stateParams were populated in one instance but not in another. Being new to angular-ui-router, I could use some assistance on this matter. Any tips would be greatly appreciated. Thank you! When I added $statePara ...

Ways to verify the functionality of a webpage once it has been loaded on my local machine's browser

I manage a website that is currently hosted on a server and being used by thousands of visitors. The site is created using Java and soy template technology. I am looking to test the frontend rendering and JavaScript files. Can this be done directly from my ...

Isolated scope in AngularJS Services: Exploring the benefits

I have a service in my Angular application that holds a Configuration structure which is used by multiple components. During the .run phase, the guiConfigService reads configurations from a .json file using the function setGuiConfig, and it can provide dat ...

Program written in the PHP language that generates output in the form of an

Currently, I am struggling with creating a PHP script that can generate JSON data in the specified format. Despite my efforts, I have not been successful in achieving this. { "authentication_credentials": { "api_key": "hybghhmimjij48fr847gt4fdf847v8 ...

Seeking a sleeker approach to composing various components with shared functions

Currently, I have a scenario where I have identical components that display data but also need to handle state manipulation and saving. There are 5 other similar components with slight differences in their functions. I am looking for a more efficient way t ...

Is there a way to retrieve the value of an HTML variable using Selenium?

Seeking assistance in determining the progress value of a video using Selenium. I understand that I need to utilize JavaScript executor, but have been unsuccessful in finding a solution so far. The element in question is: <div aria-label="scrub bar" a ...

Snowflake - JSON parsing error: unexpected character found outside string: '/'

I'm struggling with Snowflake as I try to load JSON data into a table. When attempting to load the JSON file through an external stage using an airflow dag task, I encounter the following error: ERROR - Task copy_raw_data failed to execute job 856 ( ...