Implementing AngularJS to store data in a JSON object

Imagine having an animals.json file with the following details:

{
  "animals": {
    "elephant": {
      "size": "large"
    },
    "mouse": {
        "size": "small"
    }
  }
}

Now, let's say this data is being added to the controller scope:

animalsApp.controller('animalsCtrl', function($scope, $http){
    $http.get('../../animals.json').success(function(data){
        $scope.animals = data.animals;
    });
});

Everything works smoothly until there's a need to fetch additional information from an API and update $scope.animals with it. The new data looks like this:

{
    "animal_name": "Leonardo"
}

This data is retrieved by accessing the API using the following query:

http://api.someapi.com/animals/{animals.elepahant} // returns above json

In this scenario, consider {animals.elaphant} as the result obtained from looping through the JSON, extracting specific values, querying the remote API with those variables, updating the JSON with the new data, and then returning the modified JSON in $scope.animals.

The resulting JSON structure appears as follows:

{
  "animals": {
    "elephant": {
      "size": "large",
      "name": "Leonardo"
    },
    "mouse": {
        "size": "small",
        "name": "Vader"
    }
  }
}

How can one accomplish this task?

Answer №1

Typically, one would iterate through an array of animals.

However, in this case, we are dealing with an object where the same principle applies. It is crucial to implement a closure for the loop, which can be achieved using angular.forEach().

Using for loops alone does not establish a closure and may lead to issues as the loop completes much before the response to requests is received.

$http.get('../../animals.json').success(function(data){
    $scope.animals = data.animals;
    angular.forEach(data.animals, function(v, animal_type){
       var url = 'http://api.someapi.com/animals/' + animal_type; 
       $http.get(url).success(function(resp){
           v.name = resp.animal_name;
       });
    });
});

There are other ways to write this utilizing chained promises, but I have kept it simple for now.

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

Organize database entries by categories for easy navigation

I've developed a web application centered around TV Shows to enhance my understanding of AngularJS. Within my database, I have a table containing various TV shows, each with an assigned category column. For instance, "Dexter" is categorized as "thrill ...

Retrieving elements from a JSON string within a foreach loop

@foreach (var fieldset in Model.Content.GetPropertyValue<ArchetypeModel>("MainMenuDT")) { <li>@fieldset.GetValue("linkObj")</li> } this displays: [ { "caption":"gjhg", "link":"http://localhost:2081/", "newW ...

Importing libraries in TypeScript and JavaScript are not done in the same manner

As I create my own library, I aim for it to be compatible with both javascript and typescript. tsconfig.json { "compilerOptions": { "target": "es2017", "module": "commonjs", &qu ...

Is it possible to calculate a variable within a dataset using existing data as a reference point?

Is there a way to dynamically compute some of the data variables in a Vue instance by referencing other variables and tracking their changes? new Vue({ el: '#root', data: { x: 1, y: x + 1 } }) <script src="https://cdnjs.cloudf ...

Steps to integrate the Save as PNG functionality in Vega using a customized menu

As I develop a data dashboard with Vega for visualizing outputs, I decided to customize the menu system by removing the actions dropdown. However, I still want to incorporate the "Save as PNG" option from the original dropdown (as shown in the image below) ...

How do I fix the build error that says "Operator '+' cannot be used with types 'number[]'?

The function below is designed to generate unique uuidv4 strings. function uuidv4() { return ([1e7] + -1e3 + -4e3 + -8e3 + -1e11).replace(/[018]/g, c => ( c ^ (crypto.getRandomValues(new Uint8Array(1))[0] & (15 >> (c / 4)) ...

Tips for ensuring only one submenu is open at a time

I have successfully created a responsive menu that is working well. However, I am facing an issue. I want only one menu to be open at a time. When a submenu is opened, the other menus should be hidden. How can I achieve this? Below is my Script code $( ...

Creating a dynamic canvas with a three-dimensional model using three.js: A step-by-step guide

I'm currently developing a website where I have integrated a canvas element to display a 3D object (specifically, a cube) using three.js. The canvas is housed within a div, following the guidelines found in various documentation. The issue arises wh ...

Difficulty in adjusting the height of the popover menu that appears when using the Select Validator in Material UI

I am having trouble adjusting the height of a popover that emerges from a select validator form in Material UI. Despite attempting various methods, including adding the following CSS to the main class: '& .MuiPopover-paper': { height: &apos ...

Uncovering the Image Orientation in Angular: Is it Possible to Determine the Direction Post-view or Upon Retrieval from Database?

I am currently working on creating centered and cropped thumbnails for images retrieved from a database. I came across some helpful information on how to achieve this: The resource I found is written for JavaScript, but I am using Angular 7. I am facing d ...

Having trouble with setting up local notifications in React Native's scheduling feature?

I have integrated the react-native-push-notifications npm library into my application to enable notifications. However, I am facing an issue while trying to schedule notifications using PushNotification.localNotificationSchedule. The code snippet for this ...

Converting an array of objects to an array based on an interface

I'm currently facing an issue with assigning an array of objects to an interface-based array. Here is the current implementation in my item.ts interface: export interface IItem { id: number, text: string, members: any } In the item.component.ts ...

Dividing JSON into multiple objects when an array-valued field is detected in Scala

I'm looking for a way to divide a json object in scala into multiple objects whenever there is an array valued field present. Here is the input JSON: { "name" : "test", "age" : 22, "courses" : ["math", "english"] } The desired output should ...

Update the URL routing in angularjs to point to a new controller

Within the VisualisationController, I have come across this Angular code snippet: $http.get('api/apinetwork/getnetwork').success [...] The issue lies in the fact that it is trying to access instead of . How would you suggest adjusting the UR ...

Custom AngularJS Directives for Enhancing Chrome App and Android 'Webview' Elements

I'm currently in the process of transitioning an existing Chrome packaged app to incorporate Angular. So far, everything seems to be working smoothly. However, I am facing a challenge when it comes to updating the UI from outside Angular, specifically ...

I encountered difficulty in assigning a JSON response to a variable, both with and without using JSON.parse()

I'm in the process of creating a website that, among other things (and crucially for this particular issue), stores your current location data in a variable by fetching it from the ipinfo API (https://ipinfo.io/json) After encountering the problem of ...

Tips for resolving the issue: React is unable to recognize the X prop on a DOM element

I have been experimenting with a library known as react-firebase-js for managing firebase authentication. However, my grasp of react and the concept of provider-consumer is somewhat limited. Initially, I created a large JSX construct at the top level, whi ...

Troubleshooting NPM installation failures with SQLite build

After updating to macOS Mojave and installing the latest versions of node 12.1.0, npm 6.9.0, brew 2.1.1, and Python 2.7.10 on darwin, I encountered an issue while running npm install in a package.json file for a project that includes "sqlite3": "4.0.6". ...

Server Receiving Missing Post Parameters

I've developed a straightforward $resource factory. .factory('Order', order) order.$inject = ['$resource', "ApiEndpoint", "UserRecord"]; function order($resource, ApiEndpoint, UserRecord) { return $resource(ApiEndpoint.url + & ...

Enable automatic full-screen mode on Google Chrome upon page load

I would greatly appreciate it if you could provide an answer to this question, even if it is marked as a duplicate. I have tried various solutions and sought help, but unfortunately, nothing seems to be working for me... What I really need is for the brow ...