AngularJS ng-repeat is used to iterate over data contained within a model

I am curious to know if I can utilize ng-repeat with a model structured in the following way:

Illustrative Model:

$scope.items = {
   item1:{[1,2,3,4,5]},
   item2:{[a,b,c,d,e]},
   item3:{[a1,b2,c3,d4,e5]}
};

The desired table format using ng-repeat would be as follows:

-------------------------
| Item1 | Item2 | Item3 |
-------------------------
|   1   |   a   |   a1  |
|   2   |   b   |   b2  |
|   3   |   c   |   c3  |
|   4   |   d   |   d4  |
|   5   |   e   |   e5  |
-------------------------

If achieving this layout is not feasible with the current model structure, could you kindly propose some alternatives? Your assistance would be highly appreciated. Thank you in advance.

Answer №1

If you want to modify the data model, follow these steps:

function Modification($scope) {
    $scope.items = [{
        item1: 1,
        item2: 'a',
        item3: 'a1'
    }, {
        item1: 2,
        item2: 'b',
        item3: 'b2'
    }, {
        item1: 3,
        item2: 'c',
        item3: 'c3'
    }, ...];
}

<div ng-app ng-controller="Modification">
    <table>
        <tbody>
            <th>item1</th>
            <th>item2</th>
            <th>item3</th>
            <tr ng-repeat="item in items">{{item}}
                <td>{{item.item1}}</td>
                <td>{{item.item2}}</td>
                <td>{{item.item3}}</td>
            </tr>
        </tbody>
    </table>
</div>

DEMO

Answer №2

If you are unable or unwilling to modify your data structure, or if you do not know the number of keys in advance, you can dynamically manipulate it. Below is an algorithm that can handle objects with varying numbers of keys and arrays of any length (as long as each array has the same length):

var results = { headers: [], values: [] };
angular.forEach(items, function(value, key) {
  results.headers.push(key);
  angular.forEach(value, function(inner, index) {
    results.values[index] = results.values[index] || [];
    results.values[index].push(inner);
  });
});
return results;

Once you have a transposed array, you can iterate through it programmatically:

<table ng-controller="DataController">
  <tr>
    <th ng-repeat="header in transposed.headers">{{header}}</th>
  </tr>
  <tr ng-repeat="ary in transposed.values">
    <td ng-repeat="item in ary">{{item}}</td>
  </tr>
</table>

Here's a demonstration that re-transposes the items object each time it changes: http://jsfiddle.net/BinaryMuse/BAGL5/

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

What is the best way to extract elements from an array object and store them in a separate array using JavaScript

Is there a way to extract specific values from an array object and store them in individual variables as arrays? // Given array const dummy = [ { id: 1, name: 'John', }, { id: 2, name: 'Jane', }, { id: 3, ...

The process of showcasing angularjs ng-repeat with a JSON object

I'm attempting to search for product results using AngularJS. I have retrieved a JSON object with my results, an example of which is shown below: [{"store_id":"17","user_id":"29","company_name":"Liquor R Us","company_type":"Alcohol", "phone":"(303) 5 ...

Stop ajax request when select2 is clicked

Is there a way to change the ajax call behavior in select2 drop down items so that it only retrieves data when I start typing in the search box, and not on click of the element? Your guidance on this issue would be highly appreciated. $("#ddlItems").sel ...

Determine the quantity of particular information within an array of objects

My goal is to calculate the total number of entries based on the color provided by the user. For instance, if the user enters 'red', the program should return 11. I attempted to achieve this but encountered an issue with the variable cnt not bein ...

Is there a way to show an image fetched from an axios call in a Vuejs img tag? I haven't found any solution that actually works

There are various methods to achieve this. Initially, I planned to save the image in my database and then call it from there to the view. However, I'm unsure about where to store the image and how to properly call it using :src="prizes.image_url". Th ...

Tips for altering the browser tab color on a PC or Mac with HTML or JavaScript

While I am aware of the method to change theme colors on mobile devices using <meta name="theme-color" content=" #0000ffbb" />, I prefer browsing on my laptop. Are there ways to customize browser tab appearance using HTML or JS fo ...

How to use the groupBy function in Underscore.js

{ collectionId: 1, category: 'a', collectionType: 'typea' }, { collectionId: 1, category: 'a', collectionType: 'typea' }, { collectionId: 1, category: 'b', col ...

Toggle visibility on the child DOM element of each item in the v-for loop

Here's an example of a template: <template> <table class="table table-hover"> <tbody> <tr> <th style="width:260px">Info</th> <th>Deta ...

Deciphering Korean for crawling using got

I am currently attempting to perform web scraping on a website using the got library. Below is the simple code that I have written: import got from 'got'; async function test(){ const data = await got('https://dhlottery.co.kr/store.do?m ...

Encourage users to activate the physical web feature in compatible web browsers

Is it possible to use JavaScript to encourage users to activate the physical web (and thus BlueTooth), similar to how APIs like "getUserMedia()" prompt users? UPDATE: Given that this technology is still in its early stages and not extensively supported, t ...

Can you suggest a more "ember-esque" approach to calculate this value?

Note: Due to my current situation, I must work with Ember 2.18 but I am curious if version ^3.4 has certain features that 2.x does not. I am creating a Boolean based on the values of two other Booleans. Within the class, the following code snippet is pres ...

When an absolute positioned DIV is nested inside a relatively positioned DIV, it disappears when the page is scrolled

A unique feature of my DIV is that it remains fixed at the top of the page as you scroll. This is achieved by setting its position to fixed. However, within this main container, I have another div with a relative position. While the content in the relative ...

Depending on the chosen country, it is necessary to display the corresponding state and city options

HTML: <label for="country">Country *</label> <select id="country" ng-model="statessource" ng-options="country for (country, states) in countries" ng-change="GetSelectedCountry()"> <option value=''>Select ...

Separate the navbar-brand and nav-items onto separate lines within the Bootstrap 4 navbar

I would like to arrange the navbar-brand and nav-items on separate rows. Put the navbar brand on the first row and the navigation items on the second row Existing code: <nav class="navbar navbar-expand-lg navbar-light bg-light"> <a class="nav ...

The selection option fails to update when there is a change in the ng-model

My issue involves two select tags, named Select 1 and Select 2, each with their own ng-model variables and separate methods triggered by ng-change. I am attempting to set the value of the Select 1 option from a method called by the ng-change of Select 2. H ...

What is the reason behind Intellij Code Inspection indicating that a selector is not being used?

I have a small project consisting of two files located in the same folder. App.css .App-align-left { text-align: left; } App.js import React from 'react'; import 'App.css'; class App extends React.Component { constructor(p ...

Utilizing the powerful slice function within Lodash

I am looking to create a function that takes an array and a number as input. If the number is positive, the function should place it at its corresponding index within the array. For example, if we have an array of 1,2,3,4,5 and the number 2, it should be p ...

Webpage push notifications are a convenient feature that allows websites to

Is it possible to incorporate web notifications on websites built using JSPs with jQuery, Vue, and Angular.js on the front end? Is there a method to integrate web notifications within this specific environment? ...

What causes MongoDB to modify my UTC time zone from UTC+2:00 to UTC+0 when utilizing Mongoose in conjunction with moment-timezones.js?

MongoDB recently updated their UTC time from UTC+2:00 to UTC+0. Despite attempting to include the option "{ forceServerObjectId: true }", I still encountered issues. My code relies on moment-timezones.js for creating dates, here's a snippe ...

Obtain random images from a sprite sheet using HTML5 canvas

Currently, the code is only displaying green asteroids from the sprite sheet, but I would like to randomly select and display red, pink, and green asteroids across the row in the game. Any assistance with this would be greatly appreciated. Here is the exi ...