Tips for retrieving JSON data in the correct order using AngularJS

I'm a newcomer to using AngularJS and I have an ambition to create an eCommerce website that showcases recipes. I want to fetch all the JSON data related to recipes and display detailed information in grid boxes, similar to what's shown in this example image here. However, I've encountered a problem where the order of recipes appears to be random each time the page is loaded, resulting in different recipes being displayed within the block intended for showcasing 8 recipes. It seems like there's an issue with my JavaScript code, but I'm struggling to figure out how to organize these recipes correctly.

Below is the HTML file:

<html>
<head>
    <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.0-beta.2/angular-route.min.js"></script>
    <link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
    <script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
    <script src="H:/job/Xmapp/htdocs/AngularJs/recipesController3.js"></script>
    <link rel="stylesheet" href="H:/job/Xmapp/htdocs/AngularJs/imgStyle.css">
</head>
<body>
<div ng-app="myApp" ng-controller="mainController" class="center">
    <div class="container-fluid">
        <div class="row">
            <div class="col-sm-3" ng-repeat="recipes in listOfrecipes |limitTo:8 track by $index">
                <div class="panel panel-default">
                    <div class="panel-body">
                        <div class="name"><h4> {{ recipes.Recipe.name|uppercase}}</h4>
                            <p>4 Serves</p>
                            <h4>MAIN INGREDIENT :</h4>
                            <table class="table_style">
                                <tr>
                                    <td>- {{recipes.IngredientMapping[0].Ingredient.name}}</td>
                                    <td>- {{recipes.IngredientMapping[1].Ingredient.name}}</td>
                                </tr>
                                <tr>
                                    <td>- {{recipes.IngredientMapping[2].Ingredient.name}}</td>
                                    <td>- {{recipes.IngredientMapping[3].Ingredient.name}}</td>
                                </tr>
                            </table>
                            <br>
                            <div>
                                {{recipes.Recipe.directions|limitTo:100}}
                                <a href="/" class="dotStyle"><strong>....</strong></a>
                            </div>
                            <div>
                                <img class="img" ng-src="http://164.132.196.117/chop_dev/recipe/files/image/attachment/{{recipes.Image[0].id}}/{{recipes.Image[0].attachment}}">
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>
<br>
</body>
</html>

And here is my Controller.js file:

var myApp = angular.module('myApp', []);

myApp.controller('mainController', function ($scope, $http) {
    console.log('dddddd');
    // delete $http.defaults.headers.common['X-Requested-With'];
    $scope.listOfRecipe = null;
    $scope.listOfIngredient = Array();
    $scope.listOfrecipes = Array();
    var url = "http://164.132.196.117/chop_dev/recipe/recipes.json";
    var url2 = 
    "http://164.132.196.117/chop_dev/recipe/recipes/view/";

    function first_call() {
        return $http({
            method: 'GET',
            url: url
        }).then(function (response) {
            var wait_it = false;
            $scope.listOfRecipe = response.data.recipes;
            //to get how many recipes in total in json file
            console.log($scope.listOfRecipe);
            var recipeLength = $scope.listOfRecipe.length;

            $scope.listOfIngredient = new Array(recipeLength);

            for (var j = 0; j < 100; j++) {
                $scope.listOfIngredient[j] = Array();
            }

            console.log(recipeLength);
            for (var i = 0; i < recipeLength; i++) {
                //access to different individual recipe with recipe id
                another_call($scope.listOfRecipe[i].Recipe.id);
            }
        });
    }

    function another_call(Recipeid) {
        $http.post(url2 + Recipeid + ".json", null).then(function (response2) {
            var one_recipe = response2.data.recipe
            $scope.listOfrecipes.push(one_recipe);
        });
        console.log($scope.listOfrecipes);
    }

    first_call();
});

Answer №2

As mentioned by others, utilizing a filter is likely the most effective approach. However, if you are determined to arrange the http requests in a specific order, consider implementing the another_call function as shown below:

function another_call(Recipeid, others)
{
   $http.post(url2+ Recipeid +".json", null).then(function (response2) {
       var one_recipe=response2.data.recipe
       $scope.listOfrecipes.push(one_recipe);
       var next = others.pop();
       if (next != null) another_call(next.Recipe.id, others);
       console.log($scope.listOfrecipes);
   });
}

Within the first_call's then function, instead of iterating through $scope.listOfReceipe, utilize the following code snippet:

$scope.listOfReceipe = $scope.listOfReceipe.reverse();
if ($scope.listOfReceipe.length > 0) {
   another_call($scope.listOfReceipe.pop().Recipe.Id, $scope.listOfReceipe);
}

This setup is intended to recursively execute within the promise resolution while data remains in $scope.listOfReceipe, enabling the http requests to be made orderly.

Please note: The code has not been verified for functionality.

Answer №3

When using the line ---ng-repeat="recipes in listOfrecipes |limitTo:8 track

make sure to include an orderBy function

If necessary, you can create a custom order function to specify the desired sequence This will guarantee that the order remains constant as long as the JSON data does not change

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

How to effectively share an object array between controllers when utilizing modal windows in AngularJS

I'm currently working with an array of objects that I need to share between two controllers, one of which involves a modal window. Check out the JavaScript code below: angular.module('MyApp', ['ngMaterial', 'ngMessages' ...

Sending data from a React application to a Node.js server using Axios

Hello, I am facing an issue with an axios request to post data to a Node.js server. When trying to access this data on the server, it is showing as undefined. Below is the function for posting data: function Submit() { let params={ firstName: ...

How can I securely transfer a token from an external server to a specific API endpoint?

I am currently following this process: First, I initiate an ajax call on the client side to a route named "/gettoken". Upon hitting this route, the request is routed to my Node server where I handle it using router.get("/gettoken", function etc etc). Wit ...

Experience the frustration when the Ruby on Rails Open Modal Box Link fails to work. Stay tuned for the latest update on the link

My goal is to have a Modal Popup Box open when a specific link is clicked on my page. Here is the code I added to my view file: <%= link_to_remote '+ Add Discount', :url => {:controller => "parent_wise_fee_payments", :action => "ne ...

When additional elements follow, the button ceases to function properly in JavaScript

I am working on creating a text-based idle game that involves multiple buttons and text around them. However, I have encountered an issue where the functionality stops working when I try to add text after the "Work" button. The callback function is no lon ...

Confirming the username's accuracy through an external API as part of the registration procedure

My latest project involves creating a web application specifically for Fortnite players looking to connect with other gamers. The concept is simple: users can register, log in, post, and comment within the platform. I have successfully designed the fronten ...

Tips on retrieving complete information from mongoose when the schema contains a reference

I have a schema that includes [content, name, email], and I need to retrieve all three data fields and render them on the frontend simultaneously. Can you provide an example of JavaScript code that accomplishes this? const UserSchema = new mongoose.Schem ...

Retrieve the value of a JSON array containing only a single object using jQuery

In my project, I have a jQuery file and a PHP file. If the PHP file successfully completes the process, it returns the value 2 using `echo json_encode(2)`. I am able to catch this value in the jQuery file and display a string on an HTML div without any iss ...

Vue modal fails to display when triggered by a specific query parameter

I've encountered an interesting challenge with my Vue.js app. Currently, the modal is displayed correctly when a button is clicked using the show() method: <script> export default { methods: { show() { console.log("showing modal ...

Convert the entirety of this function into jQuery

Can someone please help me convert this code to jQuery? I have a section of jQuery code, but I'm struggling with writing the rest! function showUser(str) { if (window.XMLHttpRequest) { xmlhttp = new XMLHttpRequest(); } else { ...

Issues arise when initiating the Node.js server with Gulp and encountering a breakdown in live reload functionality, specifically while working with an Angular application that utilizes html5 mode

I have been facing a persistent issue that needs solving. The Scenario: The problem arises when I start my local server with Live Reload using Gulp. My Angular app starts up without any issues, but whenever I make a file change, Live Reload breaks my ap ...

I am looking to incorporate detailed explanations within my code utilizing jsdoc

Explaining the onChange function using jsDoc in my component repository. I want to ensure that users understand the parameters it accepts. However, I'm unsure if my explanation will be clear enough for others to grasp. This is my component /** * @ty ...

NodeJS Request Body Not Populated

Currently operating with node using [email protected] and [email protected]. Within my jade page, there exists a property like this: input(type='text',class='form-control', placeholder="Username", name='username', ...

What steps can I take to troubleshoot issues when creating a React app?

While attempting to set up a react application using npx create-react-app projectreact, I encountered the following error message: PS C:\Users\ahnaa\OneDrive\Documents\Web Developent\Reaact JS> npx create-react-app project ...

Incorporating items into a dynamic array using MobX

Issue with Pushing MobX Objects to an Observable Array I'm facing a challenge when trying to push objects into an observable array in MobX and iterate over them successfully. At the starting point, I initialize the observable array: if (!self.selec ...

The ul cannot be hidden if there are no li elements within it

Currently, I am attempting to hide the unordered list (ul) on a specific page using AJAX due to certain sections of the site being Ajax-based. <ul class="sub-nav-20-m" id="filtersList_m"> </ul> Below is the code that I hav ...

Transform JSON date string into Python datetime object

When converting dates to JSON, JavaScript stores them in the following format: 2012-05-29T19:30:03.283Z However, I am struggling to convert this to a Python datetime object. I have attempted the following approaches: # This throws an error because the & ...

This code snippet, document.location.search.replace('?redirect=', '').replace('%2F', ''), is failing to execute properly in Firefox

The functionality of document location search replace redirect to another page works in Chrome, however, document.location.search.replace('?redirect=', '').replace('%2F', ''); it does not work in Firefox; instead, ...

Is there a way to execute a function only once when the submit button is clicked in a jQuery AJAX form?

I am using Django to create a website where users can create groups. To allow users to fill in group information and upload an image as the group logo, I have implemented an HTML form. In order to preview the logo before submission, I have used AJAX to upl ...

Sort, Transform, and Condense

In my code snippet, I have a loop that iterates over an array and manipulates the data: $scope.listDeColaboradoresObject.forEach(item => { item.listNmAssunto = $scope.relatorioTotalMensagensRespondidasColab .filter ...