Creating a table using ng-repeat in AngularJS on a single-level array

I have a collection of N items:

$scope.collection = ["item 1", "item 2", "item 3" ... ,"item N"]

My goal is to convert this collection into a table with X columns and N/X rows.

Is it feasible to achieve this using the ng-repeat directive?

I am aware that I can restructure the collection like this :

$scope.collection = [["item 1", "item 2", "item 3"], ["item 4", "item 5", "item 6"] ...]
and then utilize nested ng-repeat.

However, I would like to ascertain if maintaining a single-level array is also a viable option.

Answer №1

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

app.controller('homeCtrl', function($scope) {

  $scope.x = 3;

  $scope.arr = [];

  for (i = 0; i < 100; i++) {
    $scope.arr.push(i);
  }

  $scope.getColumns = function() {

    return new Array($scope.x);

  };

  $scope.getRows = function() {

    return new Array(Math.ceil(($scope.arr.length) / $scope.x));

  };

});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app">
  <div ng-controller="homeCtrl">
    Columns:
    <input type="number" ng-model="x" />

    <table border="1">
      <tr ng-repeat="i in getRows() track by $index" ng-init="idx = $index">
        <td ng-repeat="c in getColumns() track by $index" ng-init="idy=$index">{{arr[(idx*x)+idy]}}</td>
      </tr>
    </table>

  </div>
</div>

Answer №2

Great puzzle! Here's my solution:

http://jsfiddle.net/ABC123/99/

<div ng-app='myApp' ng-controller="Main">
<table>
    <tr ng-repeat="r in rows()">
        <td ng-repeat="c in columns(r)">{{ c }}</td>
    </tr>
</table>
</div>

var myApp = angular.module('myApp', []);
myApp.controller('Main', function($scope){

    $scope.arr = ["A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P"];

    $scope.columnCount = 3;

  $scope.rows = function(){
    var input = [];
    for (var i=0; i< $scope.arr.length / $scope.columnCount; i++) input.push(i);
    return input;
  };

  $scope.columns = function(row){
      var start = row * $scope.columnCount;
      var end = start + $scope.columnCount;
    var input = [];
    for (var i=start; i< end; i++) input.push($scope.arr[i]);
    return input;
  };
});

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

Applying CSS to select a different element style within a webpage

I was thinking about the possibility of linking one style to another using events like :focus or :hover in CSS alone, without the need for JavaScript. For instance, can the class "hitArea" change the background attribute of "changeArea" when it is in foc ...

How can I pick out paragraphs that don't end with a period and eliminate dashes using jQuery or JavaScript?

Here are the paragraphs I need assistance with: <p>This is the initial paragraph.</p> <p>This is the second one</p> <p>The third paragraph comes next.</p> <p>Last, but not least</p> The second and fourth pa ...

How can I display a string stored in a JSON file onto a TMP_Text component in Unity using C#?

Hi there, I'm just starting to familiarize myself with Unity and C#. Recently, I came across some code that allows me to read a json file. My goal is to extract the data from this json file and display it in a specific textfield. Let's take a lo ...

Tips for combining dvloading and required functionalities on the submit button

My form has 2 fields that must be filled out, and I used the required attribute to enforce this rule. Enter A:<input type="text" name="a" required><br> Enter B:<input type="text" name="b" required><br> <button type="submit" cl ...

Clicking a button triggers Ajax to refresh the content of a div

I have a main DIV that contains mini divs with car information arranged in rows of two. This data is fetched from a database using a query. I would like to know if it's possible to reload the main content with new data from the database when a certain ...

The transformation rotation applied in CSS must not have any impact on the styling of my span and paragraph

Snippet: .details-section{ background-color: rgb(83, 83, 83); height: 200px; } .icon-container{ border: 2px solid #c49b63; width: 90px; height: 90px; transition: 0.5s ease; } .box i{ font-size: 60px; color: black; margin-top: 13px ...

How to reach the Twitter share iframe with JavaScript/HTML

There seems to be an issue with the Twitter share button not displaying at its full width on certain pages. Upon investigation, I discovered that the iframe containing it is only set to a width of 24px, when it should actually be set to the correct width. ...

What is the best way to retrieve an array situated inside an array of objects in Angular?

My dataset consists of an array of object entries for employees, structured as shown below: [ { id: "1", name: "name", email: "email", languages: ['english', 'german', 'spanish'] }, { ...

Toggle checkbox fields based on link or checkbox selection

I need to create a functionality where specific checkbox fields (location fields) are shown or hidden based on the selection of the parent name. For example, if "United States" is selected, all US locations should appear below the United States label. I h ...

Tips for concealing a table row depending on the value of an option in AngularJS

My challenge involves integrating a dropdown menu... <select ng-model="dropdown"> <option ng-value="1">1</option> <option ng-value="2">2</option> <option ng-value="all">All</option> </select> al ...

What is the method for invoking a controller from a separate file in AngularJS?

Imagine having the following two scripts: Script 1: var app = angular.module('myApp', []); app.controller('myCtrlOfJs1', function ($scope, $http) { $http.post("url", data).success(function(data, status) { $scope.hello = data; ...

Combining arrays in JSON with the power of Groovy 2.4

Below is the JSON input I have, where I am attempting to merge scheduleDetails with the same ID: {"orderLines": [{ "ID": "001", "scheduleDetails": [{ "address": { ...

Managing AJAX Errors in PHPAJAX error handling tips for developers

My current code is only set up to display a general error message when an error occurs during execution. I want to improve it by returning specific error messages for different scenarios. However, I have not been able to find satisfactory solutions in my s ...

"Utilizing Angular within the same controller, find a way to pass data fetched from SQLite from one function to another function for onload operations

How can I pass SQ-lite retrieved data from one function to another for use on load within the same Angular controller? See below for my code: $scope.test = function(){ var datalength = ''; db.transaction(function (transaction) { ...

Retrieve data using the designated key and convert it into JSON format

If I have the following JSON array: [ {"data": [ {"W":1,"A1":"123"}, {"W":1,"A1":"456"}, {"W":2,"A1":"4578"}, {"W":2,"A1":"2423"}, {"W":2,"A1":"2432"}, {"W":2,"A1":"24324" ...

Is there a way to store the outcome of my node api request in a variable and then transmit it using Express?

Currently, I am leveraging Node to initiate an API call to a movie database. This Node API call is enclosed within an Express route. // Mandatory module requirements var express = require('express'); var router = require('./router.js&ap ...

Automated file uploading with AJAX on Firefox

After inserting a row into the database, I want to automatically upload a PDF/XML file with no user involvement. The script should be able to identify the filename and location of the file. Is there a method to achieve this task? Share your ideas in the a ...

Creating functionality that activates when specific classes are clicked in elements loaded dynamically through Ajax

I'm starting to feel a bit overwhelmed by the usage of .click events when it comes to dynamically loading content from other pages... Here's the scenario: I have a main table where the first column in each row is clickable, allowing you to load ...

how to use AngularJS filter and ng-options to format specific options as bold in a select dropdown

I am currently utilizing AngularJS ng-options to populate specific select elements. I am interested in bolding and disabling certain options. Despite trying to achieve this using the filter along with ng-options, I have been unsuccessful so far. While I ca ...

What is the process for retrieving a list of image URLs from Firebase storage and then transferring them to Cloud Firestore?

Currently, I am working on uploading multiple images to Firebase Cloud Storage simultaneously. The process involves uploading the images, obtaining their URLs upon completion, adding these URLs to a list variable called urlsList, and then uploading this li ...