Eliminate the static JSON by using an HTTP GET request instead

Currently diving into learning Angular and I have a question about how to replace a hardcoded JSON array with JSON retrieved using http get. Here is the link to the plunker that I am actively working on. In order to populate the dropdown menu at the top, I am currently using this code:

angular.module('myapp', [])
  .controller('MainCtrl', function($scope, $http) {
    var records;
    $scope.selCountry = '';
    $scope.searchText = '';
    $http.get('http://www.w3schools.com/angular/customers.php').success(function(dt) {
      //window.alert(angular.toJson(dt));

      var countries = [];
      records = dt.records;
      dt.records.forEach(function(o) {
        var c = o.Country;
        if (countries.indexOf(c) == -1)
          countries.push(c);
      });
      $scope.countries = countries;
      $scope.total = countries.length;
    });

I'm unsure if this is where I should be populating the array as well? Is this the correct approach or is there a better method to achieve this (similar to what I've done above)? Do I need to manually create an array for all objects or can I simply access the incoming JSON data. Thank you.

Answer №1

Indeed, this is the spot where you assign the api response to your scope variables. Here is an example of how you could structure it:

$http.get('https://www.example.com/api/data').then(function(response) {
  //console.log(angular.toJson(response.data));

  $scope.countries = [];
  $scope.records = response.data;
  response.data.forEach(function(item) {
    var country = item.Country;
    if ($scope.countries.indexOf(country) == -1)
      $scope.countries.push(country);
  });
  $scope.total = $scope.countries.length;
});

It's worth mentioning that the $scope.total variable is redundant in this case. You can simply access the total count by using $scope.countries.length instead.

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

ngOptions not updating the selected item in the select dropdown

My Angular code is not reflecting the selected option in the select input. Even though I have specified Hospital One to be selected, it's not happening. Can anyone figure out what might be causing this issue? I've also shared the same code snipp ...

Separating JSON objects by their key value

At the moment, I am focused on retrieving the expiry status of Azure AD applications. I have collected approximately 1700 AD applications and added a new key pair (status) to the JSON object based on the expiration date of the secret. 1) valid 2) Expired 3 ...

Cannot find property in type, and the parameter is implicitly of an unspecified type

I've been encountering this issue where I keep getting an error message. I attempted to resolve it by setting "noImplicitAny": false in tsconfig.json, but unfortunately that did not work. As for the 'Property does not exist on type' error, I ...

What is the best technique for extracting specific objects from JSON data?

Receiving a JSON response from the backend is the current scenario. However, I have the requirement to extract and pass individual objects to "handlebars.js" templates. Given this situation, how do I go about iterating through the JSON response and filte ...

Creating an asynchronous endpoint in Express

Looking for some assistance in setting up a basic endpoint using Express to practice async/await functionality. Here's the code snippet I'm working with: app.post('/products', async (req, res) => { try { console.log ...

Solutions for Showing Pop-up Tabs in React Native Webview

I have a website that displays content based on user subscription status. If the subscription is active, a book is loaded; otherwise, if it's expired, a specific page is shown: https://i.sstatic.net/HLv0B.png To enhance user experience, I preload th ...

I am experiencing difficulties in initializing a class (controller) in Nextjs version 13

I am working on an application built with Next.js where I have a controller class responsible for handling all the access functions, such as retrieving data from the database. However, I keep encountering this error message: Error [ReferenceError]: Cannot ...

Struggling with retrieving data from a JSON file within a Flutter Stateful Widget?

I encountered an issue while loading data from a JSON file. I suspect the problem lies in fetching the data. Any insights on what might be causing this? Although I am not an expert Flutter developer, it's more of a hobby for me so please bear with me ...

How can I prevent text highlighting on a website?

Is there a way to lock the copy button on my site without restricting the save as button, which is activated by right click? I want users to be able to save the website as an HTML file, but prevent them from copying text. Can this be achieved using Javas ...

What is the process for creating a sub-menu for a dropdown menu item in Bootstrap 5?

https://i.sstatic.net/o4FLn.pngthis is my code which i have created this navigation bar with bootstrap and all of its drop downs but i want to add another drop down to the services drop down section inside of webdevelopment but it can't any easy solut ...

error encountered: invalid JSON format in response body while deploying Next.js application on Vercel

The application compiles successfully on local machines and functions properly on both the local production server and development server. The API utilized to retrieve data is also functioning without any issues. Here is the snippet of code that is causin ...

How to retrieve the $0 element using Python Selenium

There is an unnamed element I can only access with a dollar sign: console.log($0); "100" In Python Selenium, how can I retrieve this element? I attempted the following: my_value=driver.find_element(By.NAME,"$0") However, it resulted i ...

Extracting JSON values using special characters with common_schema

I am utilizing the extract_json_value function from common_schema to json_decode a field within my MySQL database. It is working well, except for handling accents. SELECT common_schema.extract_json_value(value,'prenom') as prenom FROM metadata w ...

The error encountered is an unhandled rejection with a message stating "TypeError: Cannot access property 'username' of null

My tech stack includes NodeJS, PassportJS, MySQL, and Sequelize (ORM for MySQL). The following code snippet is taken from my Passport.JS file. Whenever a user registers on my website, an error is returned if the username or email is already in use. If both ...

What are some strategies for blocking URL access to a controller's method in Rails 3?

My goal is to enhance my Rails 3 application by integrating Javascript/jQuery code that retrieves data from the server and updates the page based on the fetched information. I am considering implementing jQuery's $.get() method for this purpose: $.g ...

Using Angular's ng-repeat directive to iterate over an array from JavaScript

I am attempting to display an array in the HTML HTML: <div class="personWrapper" ng-repeat="message in messages"> <p>{{message}}</p> </div> JS: var app = angular.module('matcherApp', [ "ngRoute", "ngStorage" ] ...

Mapping geographic coordinates with a null projection using D3

With d3.geo.path having a null projection due to TopoJSON already being projected, it can be displayed without any additional transformation. My goal is to plot data in the format of [longitude, latitude] on a map. Here is a simplified version of my code: ...

What steps are needed to resolve the issue of inserting data into a database using Sequelize with Node Express and M

I am currently in the process of developing a straightforward registration form that will lead to additional CRUD operations using node.js. So far, I have set up the MySQL database and completed the modeling and connection with Sequelize. I have also desi ...

Filtering out duplicate names from an array of objects and then grouping them with separator IDs can be achieved using JavaScript

Imagine we have an array [ {id: 1, label: "Apple"}, {id: 2, label: "Orange"}, {id: 3, label: "Apple"}, {id: 4, label: "Banana"}, {id: 5, label: "Apple"} ] We want the output to be like this [ {id: 1~3~5, l ...

How to define an index signature in Typescript that includes both mandatory and optional keys

I am on a quest to discover a more refined approach for creating a type that permits certain keys of its index signature to be optional. Perhaps this is a scenario where generics would shine, but I have yet to unlock the solution. At present, my construc ...