Creating a table using Ng-repeat in AngularJS: A Step-by-Step Guide

I'm trying to figure out how to create the table below using ng-repeat. Unfortunately, I don't have permission to modify the json structure so I need to work with it as is.

Here's my json:

$scope.carCollection = {
    'Toyota': [
        {
            'model': 'Corolla',
            'price': '20.000,00',
            'tag': ['a', 'b']
        },{
            'name': 'Hilux',
            'price': '31.000,00',
            'tag': ['b', 'c']
        }
    ],
    'Honda': [
        {
            'model': 'Civic',
            'price': '18.000,00',
            'tag': ['c']
        }
    ]
};

And here's the HTML table format I want to achieve:

<table>
    <tr>
        <td>Producer</td>
        <td>Model</td>
        <td>Price</td>
        <td>Tags</td>
    </tr>
    <tr>
        <td>Toyota</td>
        <td>Corolla</td>
        <td>20.000,00</td>
        <td>a b</td>
    </tr>
    <tr>
        <td>Toyota</td>
        <td>Hilux</td>
        <td>31.000,00</td>
        <td>b c</td>
    </tr>
    <tr>
        <td>Honda</td>
        <td>Civic</td>
        <td>18.000,00</td>
        <td>c</td>
    </tr>
</table>

Any help would be greatly appreciated! Thanks!!!

Answer №1

Check out the ng-repeat documentation here:

https://docs.angularjs.org/api/ng/directive/ngRepeat

$scope.friends =
          [{name:'John', phone:'555-1212', age:10},
           {name:'Mary', phone:'555-9876', age:19},
           {name:'Mike', phone:'555-4321', age:21},
           {name:'Adam', phone:'555-5678', age:35},
           {name:'Julie', phone:'555-8765', age:29}];

<div ng-controller="ExampleController">
  <table class="friend">
    <tr>
      <th>Name</th>
      <th>Phone Number</th>
      <th>Age</th>
    </tr>
    <tr ng-repeat="friend in friends">
      <td>{{friend.name}}</td>
      <td>{{friend.phone}}</td>
      <td>{{friend.age}}</td>
    </tr>
  </table>

Answer №2

Before displaying your data in the view, you have the option to format it in your controller. The example below demonstrates the use of one-time bindings represented by ::.

One-time binding prevents the expression from being recalculated once it stabilizes, thereby enhancing page loading speed by reducing the number of watchers.

Controller

(function(){

function Controller($scope) {

  $scope.carCollection = {
      'Toyota': [
          {
              'model': 'Corolla',
              'price': '20.000,00',
              'tag': ['a', 'b']
          },{
              'model': 'Hilux',
              'price': '31.000,00',
              'tag': ['b', 'c']
          }
      ],
      'Honda': [
          {
              'model': 'Civic',
              'price': '18.000,00',
              'tag': ['c']
          }
      ]
  };

  //Function to format data
  function format(data){
    //Return a flatten array
    return [].concat.apply([], Object.keys(data).map(function(key){
      //Map our data object
      return data[key].map(function(elm){
        //Add brand property with the current key
        elm.brand = key;
        //Join tag array value  
        elm.tag = elm.tag.join(' ');
        return elm;
      });
    }));
  }

  //Call format function
  $scope.carCollection = format($scope.carCollection);

}

angular
.module('app', [])
.controller('ctrl', Controller);

})();

In the end, you will have a flat array that can be easily iterated over.

HTML

<body ng-app='app' ng-controller='ctrl'>

  <table>
    <tr>
        <td>Producer</td>
        <td>Model</td>
        <td>Price</td>
        <td>Tags</td>
    </tr>
    <tr ng-repeat="item in ::carCollection">
      <td>{{::item.brand}}</td>
      <td>{{::item.model}}</td>
      <td>{{::item.price}}</td>
      <td>{{::item.tag}}</td>
    </tr>
  </table>

</body>

Visit the Working Plunker to see this code in action.

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

AngularJS service functionality fails to execute in straightforward app

Having trouble with my simple Angular app, can't seem to figure out what's wrong. The code is available on Plunker at the following link: http://plnkr.co/edit/QQkP2HB6VGv50KDdBPag?p=preview. It's throwing an error: Uncaught Error: [$injector ...

issue with accessing instant state modification via useEffect

I am currently learning about React Hooks While I try to render a list from an array and remove the first element on click, the state gets updated in the handleclick function but it doesn't render correctly export default function App() { const [na ...

What causes the React Query cache to be cleared upon page reload?

Hi there, I am new to Next.js and React Query. I would really appreciate any help or advice. I apologize for any mistakes in my English language skills. Currently, I am using Next.js v12 and React Query v3, along with the React Query DevTools. On one of ...

JavaScript's Ajax request seems to be stagnant and inactive

Having some difficulties with the code below. It triggers an alert correctly, but the ajax part doesn't seem to be functioning. No errors or indications of what's wrong. $(document).on('change', '.department_select', function ...

Creating a clickable button within an image container using Bootstrap 5

I am attempting to create a button inside an img element, specifically in the center of that img element within Bootstrap 5. The image is not being used as a background on the grid and I am applying some hover animations to zoom in. I am curious if there ...

I am encountering challenges with React.js implemented in Typescript

Currently, I'm grappling with a challenge while establishing a design system in ReactJS utilizing TypeScript. The issue at hand pertains to correctly passing and returning types for my components. To address this, here are the steps I've taken so ...

What is the best way to set an array as the value for a state variable?

Looking at my function, I have the following situation: execute(e) { let { items } = this.context; let array: number[] = []; for (var i = 0; i < 2; i++) array = [...array, i]; this.setState( { items: array, } ) ...

Using Cucumber for testing javascript-loaded content can be incredibly powerful and effective in ensuring the functionality

As I develop my Rails application, I've decided to incorporate a combination of Test Driven Development and Behavioral Driven Development into my process. The challenge arises as my app utilizes the MochaUI web application user interface framework, w ...

What is the best way to utilize an Angular service method from a controller?

As a newcomer to Angular, I have created an 'Employee Search' Service module. Let's take a look at the code: // Employee Search Service app.service('employeeSearchService', function($http, resourceServerAddress){ this.empList ...

Organizing information in local storage using an array and converting it to a string

After storing user inputs (Worker's name, Car Vin, Start time and End time) in the local storage, you want to sort the employees' names in alphabetical order. The question is where should the code be placed and how should it be written? // Car C ...

Obtaining events from the calendar in Ionic's AngularJS UI based on the selected month

Hey there, I'm new to angularjs and trying to use the jquery full-calendar within the angular version, which can be found at http://angular-ui.github.io/ui-calendar/. Here's my question: I am able to fetch all events on load. Is it possible to fe ...

Is there a way to make JavaScript function properly with PHP-generated content?

I have a PHP file that loads a variety of forms depending on an identifier passed through a GET request. Everything is functioning properly, except for my JavaScript/jQuery code. Is there a way I can refresh the JavaScript to make it work with the form? ...

The Google Maps API has been successfully initialized, however, it is experiencing difficulties being displayed on the webpage

I have been successfully using a custom Google API on various web pages. However, I encountered an issue where the map API loads successfully but is not displaying on a specific web page. Below are the relevant code snippets: <html> <head> &l ...

Utilizing the map function to modify the attributes of objects within an array

I have a data structure with unique IDs and corresponding status keys. My goal is to count how many times each status repeats itself. Here's an example of my data structure: const items = { id: 2, status_a: 1, status_b: 1, status_c: 3 }; Below is the ...

Restricting the number of lines within a paragraph in Angular 2

Is there a method to limit the number of lines in a <p> tag and add an ellipsis (...) at the end? Using character count for truncation doesn't work well as the width of the element varies according to device screen size. ...

Dealing with asynchronous requests in server-side node applications

Currently, I am in the process of constructing a basic node service that carries out the following functionalities: Handles incoming GET requests from web clients Parses the parameters provided Utilizes these parameters to asynchronously query another RE ...

Is it possible to invoke this JavaScript function like this?

Is there a way to call a function like item_edit.say hello by passing it as a string on the window object (similar to the last line in the snippet below)? var arc={ view: { item_edit: {} } }; arc.view.item_edit={ say_hello: function(){ alert(' ...

Utilizing NodeJS to initiate an http request and interact with a hyperlink

I am implementing website conversion testing and want to modify this code so that 10% of the http requests also click on a specific #link within the page. What additional code do I need to achieve this? var http = require('http'); http.createSer ...

The function named updateContact is not defined, even though it has been declared

Presented below is Angular code snippet: @Component({ selector: 'app-detail-view', templateUrl: './detail-view.component.html', styleUrls: ['./detail-view.component.css'] }) export class DetailViewComponent implements O ...

A guide to implementing v-for with intervals in Quasar carousel components

I need help making my blog summary page more dynamic by using a q-carousel to display 3 blog posts per slide. I want to create an array with all the blog posts and loop through it with v-for to populate each slide dynamically while keeping the pagination l ...