Using AngularJS ng-repeat to iterate through all IDs

My application relies on Angular for functionality.

In the database, I fetch data stored in an array with various elements such as:

$ordersall[$count] = array(  
"orderID" => $looporders["orderID"],
"customerID" => $looporders["customerID"],
"customerName" => $customerName,
"orderDate" => $looporders["orderDate"],
"orderDeliveryDate" => $looporders["orderDeliveryDate"],
"orderStatus" => $looporders["orderStatus"],
"orderdetailID" => $row["orderdetailID"],
"productTitle" => $productTitle,
"productPrijs" => $productPrijs,
"aantal" => $row["orderdetailAantal"],
"extras" => "",
"extrasprice" => ""            
);

I want to display this data for each ORDERID. For every ORDERID, I aim to showcase customerName, orderDate, and specific order details like products, prices, extras, etc. It's important to note that a single order ID (e.g., 5) may have multiple order details including different product names, prices, extras, and more.

To handle a singular order ID, here's how I've approached it:

Angular

app = angular.module('app', []);
app.controller("NavCtrl",function($scope,$http){
var serviceBase = 'api/';
$http.get(serviceBase + 'orderoverview/58').then(function (results) {
    $scope.categories = results.data;
    $scope.getTotal = function(){
var total = 0;
for(var i = 0; i < $scope.categories.length; i++){
    var categories = $scope.categories[i];
    total += (categories.productPrice * categories.orderdetailAantal);
    if(categories.extra1 != "")
    {
      total += categories.extrasPrice;
    }        

}
return total;
}
});
});

HTML

   
<div class="col-md-3" ng-controller="NavCtrl">
    <div class="sm-st clearfix">
        <!--span class="sm-st-icon st-red"><i class="fa fa-check-square-o"></i></span-->
        <div class="sm-st-info">
            <i class="fa fa-square"></i>
            <span>Sander Hofman</span>
            <p>1 minute</p>
            <ul>
                <li ng-repeat= "p in categories" ng-hide="categories.extra1.length"> 
                    {{p.orderdetailAantal}}  {{p.productTitle}} <br> 
                    + {{p.extra1}} {{p.extra2}} {{p.extra3}} {{p.extra4}}
                </li>
                <li class="divider"></li>
            </ul>
            <p class="totalprice">{{ getTotal() }} euro</p>
        </div>
   </div>
</div>    

How can I accomplish having a list item in HTML for each orderID along with all its associated order details?

Example:

OrderID: 5

OrderDetail1: Product Title, Price, Quantity

OrderDetail2: Product Title, Price, Quantity

OrderDetail3: Product Title, Price, Quantity

OrderID6:

OrderDetail1: Product Title, Price, Quantity

JSON SAMPLE

[
{"orderID":4,"customerID":1,"customerName":"Sander Hofman","orderDate":"2015-04-20 09:49:06","orderDeliveryDate":"2015-04-20","orderStatus":"done","orderdetailID":2,"productTitle":"Sexy Teacher","productPrijs":4,"aantal":1,"extras":"","extrasprice":""},
{"orderID":5,"customerID":2,"customerName":"Jelle Hofman","orderDate":"2015-04-20 12:05:09","orderDeliveryDate":"2015-04-20","orderStatus":"prepare","orderdetailID":3,"productTitle":"The Coach","productPrijs":3,"aantal":1,"extras":"","extrasprice":""},

{"orderID":5,"customerID":2,"customerName":"Jelle Hofman","orderDate":"2015-04-20 12:05:09","orderDeliveryDate":"2015-04-20","orderStatus":"prepare","orderdetailID":4,"productTitle":"The Virgin","productPrijs":3.2,"aantal":1,"extras":"","extrasprice":""},

{"orderID":5,"customerID":2,"customerName":"Jelle Hofman","orderDate":"2015-04-20 12:05:09","orderDeliveryDate":"2015-04-20","orderStatus":"prepare","orderdetailID":5,"productTitle":"Sexy Teacher","productPrijs":4,"aantal":3,"extras":"","extrasprice":""},

{"orderID":22,"customerID":11,"customerName":"Tom Welslau","orderDate":"2015-04-20 14:15:12","orderDeliveryDate":"2015-04-20","orderStatus":"prepare","orderdetailID":22,"productTitle":"The Virgin","productPrijs":3.2,"aantal":1,"extras":"","extrasprice":""},

{"orderID":22,"customerID":11,"customerName":"Tom Welslau","orderDate":"2015-04-20 14:15:12","orderDeliveryDate":"2015-04-20","orderStatus":"prepare","orderdetailID":23,"productTitle":"The Virgin","productPrijs":3.2,"aantal":1,"extras":"","extrasprice":""}
]

Answer №1

The issue may lie in the format of the server's JSON response.

If the JSON data were structured as nested arrays (each order containing an array of products), you could easily handle it with two ng-repeats.

<li ng-repeat="p in categories" ng-hide="categories.extra1.length">
    {{p.orderID}}
    <ul>
        <li ng-repeat="product in p.products">
            {{product.title}}
        </li>
    </ul>
</li>

Perhaps adjusting how the server sends JSON data could be a potential solution? (if feasible)

Answer №2

One approach to streamline the display of orders is to present a list of orders initially. Upon selecting a specific order, users can then be directed to a separate view for detailed order information. This method enhances scalability. If you wish to proceed with your current approach, consider utilizing a nested ng-repeat as outlined below:

<div ng-repeat="order in orders">
<span>{{order.orderID}}</span>
<span>{{order.customerID}}</span>
<span>{{order.customerName}}</span>
<span>{{order.orderDate}}</span>
<span>{{order.orderDeliveryDate}}</span>
<span>{{order.orderStatus}}</span>

<div ng-repeat="orderDetail in order.orderDetails">
    <span>{{orderDetail.orderdetailID}}</span>
    <span>{{orderDetail.productTitle}}</span>
    <span>{{orderDetail.productPrijs}}</span>
    <span>{{orderDetail.aantal}}</span>
    <span>{{orderDetail.extras}}</span>
</div>

This setup assumes that each order in your JSON data contains all corresponding order details.

Below is an example of JSON data illustrating this point:

[{"orderID":4,"customerID":1,"customerName":"Sander Hofman","orderDate":"2015-04-20 09:49:06","orderDeliveryDate":"2015-04-20","orderStatus":"done", orderDetails:[ {"orderdetailID":10,"productTitle":"Sexy Teacher","productPrijs":4,"aantal":1,"extras":"","extrasprice":""}, {"orderdetailID":11,"productTitle":"Sexy2 Teacher","productPrijs":4,"aantal":1,"extras":"","extrasprice":""}, {"orderdetailID":12,"productTitle":"Sexy3 Teacher","productPrijs":4,"aantal":1,"extras":"","extrasprice":""}, {"orderdetailID":13,"productTitle":"Sexy4 Teacher","productPrijs":4,"aantal":1,"extras":"","extrasprice":""}, {"orderdetailID":14,"productTitle":"Sexy5 Teacher","productPrijs":4,"aantal":1,"extras":"","extrasprice":""} ]}, {"orderID":5,"customerID":2,"customerName":"Francis Ezengige","orderDate":"2015-04-20 09:49:06","orderDeliveryDate":"2015-04-20","orderStatus":"done", orderDetails:[ {"orderdetailID":20,"productTitle":"Sexy Teacher","productPrijs":4,"aantal":1,"extras":"","extrasprice":""}, {"orderdetailID":21,"productTitle":"Sexy2 Teacher","productPrijs":4,"aantal":1,"extras":"","extrasprice":""}, {"orderdetailID":22,"productTitle":"Sexy3 Teacher","productPrijs":4,"aantal":1,"extras":"","extrasprice":""}, {"orderdetailID":23,"productTitle":"Sexy4 Teacher","productPrijs":4,"aantal":1,"extras":"","extrasprice":""}, {"orderdetailID":24,"productTitle":"Sexy5 Teacher","productPrijs":4,"aantal":1,"extras":"","extrasprice":""} ]}]

Analyzed closely, you'll notice that each primary order entry is followed by an "orderDetails" field containing an array of objects pertaining to specific order details. In the provided sample, there are 2 orders with 5 items in their respective orderDetails arrays. The ng-repeat iterates through all the orders and further through each item within orderDetails for every order.

To implement this structure, ensure your server returns JSON data formatted similarly. Customization may vary based on your server type.

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

Exploring timezones using moment.js

I have received scheduledTime and timezone data from an API, for example: scheduledTime: 1603890000000 timezone: "EDT" My goal is to display this information in the user's device timezone, such as CST. What would be the most effective approach to ach ...

Capture the checked checkbox value and store it as a string

Is there a way to save the value from a checkbox into a string? <label style="color:black; text-decoration:none; font-size:15px" href="#"> <input type="checkbox" ng-model="diet.v1" ng-true-value="'&diet=high-fiber&apos ...

concealing the dropdown in React upon clicking outside of it

I have been delving into learning React by challenging myself with a React problem. The code challenge I'm facing involves trying to close a drop-down when clicking outside of it. Despite my efforts to debug, I haven't had much luck in solving th ...

Attempting to integrate AngularJS with the CodeIgniter framework

I am currently facing an issue while trying to integrate AngularJS with Codeigniter. Despite not receiving any errors, the data is not displaying as expected. I am eager to learn how to develop a RESTful application using AngularJS and Codeigniter. If anyo ...

What is the best way to set the value of the days in a month to a div

I've been experimenting with creating a calendar using javascript, HTML, and CSS on my own. I managed to achieve some functionality like obtaining the current month and year as well as the previous month and year by clicking a button in HTML. However, ...

Guide on effectively sorting the second level ng-repeat data in a table

I have a collection of data objects that I want to present in a tabular format with filtering capabilities. The current filter, based on the 'name' model, successfully filters the nested object 'family'. However, it does not function as ...

ASP.NET Core does not support jQuery.validate functionality

After successfully creating a functional jQuery.validation form using HTML, CSS, and JS with dependencies like jQuery and Validation, I encountered an issue when implementing the same code in a clean ASP.NET Core web project. It seems that my custom valida ...

Tips for transferring the clicked value to the next page

Recently, I started working with Ionic and developed an application using it. Now, I am facing a challenge where I need to pass the value from the first page to the second page. To illustrate this more clearly, I have attached two photos. Here is the imag ...

What is the best way to retrieve chosen values from a Bootstrap multiple selectpicker?

Below is an example of a select element with the multiple attribute: <select id="dd-personnels" onchange="personnelChange()" asp-items="Model.Personnels" multiple data-max-options="1" class="form-control form ...

Function for masking phone numbers is adding additional "x's" to the input field

My phone number formatting script is supposed to add dashes after the third and sixth characters, as well as insert an "x" after the 10th character for extensions. However, it is adding extra "x's" after the 12th character, resulting in the incorrect ...

Using axios.spread() allows for caching of my API requests, a feature that is not available when

Thank you for taking the time to read this. I find myself in a peculiar situation where I am required to invoke multiple CMS API routes from my server to incorporate their response.data into an object that will later be transferred to the client side. The ...

Is there a way to stop TinyMCE from adding CDATA to <script> elements and from commenting out <style> elements?

Setting aside the concerns surrounding allowing <script> content within a Web editor, I am fully aware of them. What I am interested in is permitting <style> and <script> elements within the text content. However, every time I attempt to ...

Use Angular filter to display data only from the 'last week' when clicking

As a beginner in Angular working on my first module, I have found this article to be very helpful. My goal is to filter data based on last week's records. Currently, I am able to identify the days between the current date and a given date in my MySQL ...

What is the reason for Next.js and Gatsby.js necessitating the installation of Node.js, while React.js does not have that requirement?

Have you ever thought about the connection between Next.js and Gatsby.js, both being built on React.js? Could it be that the development environments are Node applications themselves? Or maybe there's something else I'm not seeing? While I have ...

Unending cycle when integrating AngularJS with Laravel

I am struggling with an issue while integrating ngRoute with Laravel framework. Within my routes.php file: App::missing(function($exception) { return File::get(public_path() . '/angular.html'); }); This is the content of my angular.html fi ...

What is the best method for transferring HTML tables to Excel with multiple tabs?

I have created a code that exports an HTML table into an Excel file. However, I now need to export multiple HTML tables into different tabs within a single Excel file. Here is the current code: Currently, when I click "Export To Excel," the Excel file is d ...

Teaching the render engine: The process of ReactJS guiding the render engine through updating the DOM component

I recently learned that ReactJS utilizes Virtual DOM to efficiently compare and update only the necessary parts of the actual DOM node, rather than refreshing all nodes. It's interesting how React instructs the render engine to target specific nodes f ...

Error encountered when trying to save Mongoose model - "Cannot use $inc on a non-numeric value"

Currently, I have set up 2 mongoose models in separate files. const userSchema = new mongoose.Schema({ name:{type: String, required: true}, postHistory:[{type: mongoose.Schema.Types.ObjectId, ref: "Posts"}] )}; module.exports = mongoose.model(&q ...

Issue with embedding Instagram on Safari browser

My challenge involves dynamically creating an Instagram feed using AJAX. After encountering rendering issues, I turned to research and stumbled upon the following helpful response: The solution proposed was to call this line of code... window.instgrm.Emb ...

Using AJAX within the $.when function to extract the first character from the returned string

Currently, I am utilizing an AJAX call by using $.when to wait for the completion of that specific ajax request and then continue with processing the subsequent ajax request inside. The code block below demonstrates where the $.when method is being invoke ...