Implement the insertion of JSON items in real-time by leveraging the power of Angular JS and

I'm facing a challenge trying to insert JSON items into a dynamic list:

The structure of my JSON file is as follows:

[
{
"id":"34",
"City":"New York",
"Country":"USA"
},
{
"id":"22",
"City":"Las vegas",
"Country":"USA"
},
{
"id":"44",
"City":"Paris",
"Country":"France"
},
{
"id":"45",
"City":"Lyon",
"Country":"France"
}
]

I aim to display it in this format:

Below is the code snippet I am using:

<div ng-controller="customersCtrl"> 
<div class="list">
<div ng-repeat="c in cities">
<div class="item item-divider" >
{{ c.Country }}
</div>
 <a class="item" href="#" ng-repeat="ci in cities" ng-if="c.Country == ci.Country"> {{ ci.City }} </a>
</div>

var app = angular.module('starter', []);
app.controller('customersCtrl', function($scope, $http) {
$http.get('data.json')
       .then(function(result){
          $scope.cities = result.data;                
        });

});

The current output displayed is like this:

Answer №1

To easily display the data, it is recommended to preprocess the information to reveal its underlying structure. Utilizing nested repeaters can then help organize and showcase the data effectively.

angular.module('cityModule', []).
controller('CityController', ['$scope',
  function($scope) {
    var rawData = [{
      "id": "34",
      "City": "New York",
      "Country": "USA"
    }, {
      "id": "22",
      "City": "Las Vegas",
      "Country": "USA"
    }, {
      "id": "44",
      "City": "Paris",
      "Country": "France"
    }, {
      "id": "45",
      "City": "Lyon",
      "Country": "France"
    }];

    $scope.citiesByCountry = {};
    
    for (var i = 0; i < rawData.length; i++) {
      var city = rawData[i];

      if ($scope.citiesByCountry[city.Country] == undefined) {
        $scope.citiesByCountry[city.Country] = {};
        $scope.citiesByCountry[city.Country].name = city.Country;
        $scope.citiesByCountry[city.Country].cities = [];
      }

      $scope.citiesByCountry[city.Country].cities.push(city);
    }

  }
]);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>

<body ng-app="cityModule">
  <div ng-controller="CityController">
    <div ng-repeat="(countryName, country) in citiesByCountry">
      <h1>{{country.name}}</h1>
      <div ng-repeat="city in country.cities">
        {{city.City}}
      </div>

    </div>
  </div>
</body>

Answer №2

One reason for this issue is that the first loop iterates through a list of 4 items without any logic to prevent duplicates of countries already listed.

Problem

<div ng-repeat="c in cities">
<div class="item item-divider" >
{{ c.Country }}

Solution: Implement a filter to display only unique Countries (which may require creating a separate list of unique countries).

Unique Filter

app.filter('unique', function() {
   return function(collection, keyname) {
      var output = [], 
          keys = [];

      angular.forEach(collection, function(item) {
          var key = item[keyname];
          if(keys.indexOf(key) === -1) {
              keys.push(key);
              output.push(item);
          }
      });

      return output;
   };
});
<div ng-repeat="c in cities | unique: 'Country'"></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

Unable to assign value to Angular scope variable

Currently, I am delving into Angular JS as a learner. My attempt at using $http to set the corresponding value to the scope variable seems to be failing. Below is a snippet of the HTML code I am working with: <div ng-app="fileapp" ng-controller="myctl" ...

Linking controller scope to service characteristics

Recently, I have been exploring the utilization of services within controllers and specifically binding scope properties on a controller to properties in a service. In reviewing the code snippet below, I noticed that the $scope.stockCountProp in my contro ...

Tips for building a responsive dropdown menu using data from a database query

Currently, I am fetching a list of companies from Firestore and attempting to display them as options in a dropdown menu. While the companies state is being populated correctly from Firestore, the options are not being created or updated dynamically. How c ...

Utilize Jquery to dynamically modify the content on a webpage

I am looking to use Tampermonkey in order to reverse the text on a specific website, like BBC News. I have already started working on a script that can replace certain text, but I am facing difficulty in accessing all the text present on the page efficient ...

Tips for dynamically updating the id value while iterating through a class

Here's the HTML snippet I am working with: <div class="info"> <div class="form-group"> <label class="control-label col-sm-2">Title</label> <div class="col-xs-10 col-sm-8"> <inpu ...

Clicking on a DIV using jQuery, with anchor elements

I have a method for creating clickable divs that works well for me: <div class="clickable" url="http://google.com"> blah blah </div> Afterwards, I use the following jQuery code: $("div.clickable").click( function() { window.location ...

Eliminate time elements that are in close proximity from a JSON array

In my possession is an array of JSON objects, each containing timing and data. Essentially, every element includes timing, ID, and user information as shown below: [ { "id": "abc", "ts": "2017-08-17T20:42:12.557229", "userid": "seb" } ...

Whenever my NodeJs encounters an unhandledPromise, it throws an error

exports.createNewTour = async (request, response) => { try { const newlyCreatedTour = await Tour.create(request.body); res.status(201).json({ statusCode: "success", details: { toursData: newlyCreatedTour, }, ...

Navigating to a new page by selecting a row in a material-ui table

Within my project, there is a file labeled route-names.js containing the following entry: export const REVIEW_FORM_URL = '/custom-forms/:customFormId'; In one of my material-ui tables with multiple rows, clicking on a row reveals the id as ...

AXE - Asp Xtreme Evolution - A cutting-edge JSON parser designed specifically for classic ASP development

Is there anyone who has successfully used this and got it to work? I'm encountering some issues with a JScript error and I'm unsure about how to resolve it. For more information on the product, you can refer to the following links. It's a J ...

Is it possible to dynamically load a specific div when the page loads, relying on the

I am using JQuery SlideUp and slideDown methods to toggle the visibility of panels. How can I load or display the first record's contact information as a default? Currently, it loads blank because I set the panel's display property to none: < ...

The triggering of routing in Next.js is not established by useEffect

I'm facing an issue with my Next.js dynamic page that uses routing based on steps in the state. The route is supposed to change whenever a step value changes, like from null to "next" or back. However, the useEffect hook doesn't seem to be reacti ...

Obtaining a JSON file using Python

Whenever I click on a link, it triggers a "save as" dialog box for a .pst file. Due to the large size of 500 MB, I am looking for a way to save the file directly without opening it as 'sample.txt'. Is there a workaround for this issue? import u ...

Using AngularJS to transfer data from a datepicker to an ng-model

I am currently trying to figure out how to pass the date from a datetimepicker into the model. Unfortunately, I am facing some challenges with this process. I wish I could provide a demo of the issue on a fiddle, but I am unsure of how to do so due to the ...

Attempting to rename the "like" button in Django Ajax, however encountering difficulties

My button is currently functioning, but it's embedded within a Django for loop. I want to move the JavaScript logic to a separate file, but before that, I need to rename it appropriately. Check out this excerpt from my code: {% for post in posts %} ...

The HTML checkbox remains unchanged even after the form is submitted

On a button click, I have a form that shows and hides when the close button is clicked. Inside the form, there is an HTML checkbox. When I check the checkbox, then close the form and reopen it by clicking the button again, the checkbox remains checked, whi ...

What is the best way to implement my custom toolbar button to utilize the form's validation function within react-admin?

I have developed a unique Toolbar with a custom button that is supposed to mimic the behavior of the standard SaveButton but also perform additional actions after the form is submitted. The form should only be able to submit if it passes validation, and an ...

Challenges associated with utilizing img src in JavaScript

I am facing a simple issue. I have carInfo data retrieved from a JSON file, but I am struggling to correctly parse the img source stored in the variable $imgsrc instead of treating it as a string called "$imgsrc". This data needs to be appended to my HTML ...

Are your file uploaders malfunctioning by saving empty image files?

I am currently working on a file uploader using JavaScript and Classic ASP. The process involves importing an image into a canvas, converting it to a base64 URL, and then sending that URL to the ASP script for decoding and downloading. Although my AJAX re ...

Changing a date string to MM DD format in React without using plain JavaScript

I'm familiar with how to handle this outside of React. My issue is that I have a date string coming from an API within an object, and I need to reformat it. The current format is "2022-12-13T06:00Z" but I want it to display as "December 13". The objec ...