Elevated structuring: Encompassing ngRepeated elements within Angular.js

You are working with an array of objects and need to apply a specific structure to every set of elements during iteration

If you want:

Each (element) to wrap around every 4 consecutive ng-repeated elements

wrap
  ng-repeated-element
  ng-repeated-element
  ng-repeated-element
  ng-repeated-element
/
wrap
  ng-repeated-element
  ng-repeated-element
  ng-repeated-element
  ng-repeated-element
/

Every 2 groups of 4 ng-repeated elements to be enclosed by the same (element)

complex
  wrap
    ng-repeated-element
    ng-repeated-element
    ng-repeated-element
    ng-repeated-element
  /
  wrap
    ng-repeated-element
    ng-repeated-element
    ng-repeated-element
    ng-repeated-element
  /
/
complex
  wrap
    ng-repeated-element
    ng-repeated-element
    ng-repeated-element
    ng-repeated-element
  /
  wrap
    ng-repeated-element
    ng-repeated-element
    ng-repeated-element
    ng-repeated-element
  /
/


Regular use of ng-repeat:

<div ng-controller="ExampleController as example" >      
  <div ng-repeat="ex in example.arr">
    <span>{{ex.a}}</span>
    <span>{{ex.b}}</span>
  </div>
</div>

will display:

<div ng-controller="ExampleController as example" >      

  <div ng-repeat="ex in example.arr">
    <span>a</span>
    <span>b</span>
  </div>
  <div ng-repeat="ex in example.arr">
    <span>a</span>
    <span>b</span>
  </div>
  <div ng-repeat="ex in example.arr">
    <span>a</span>
    <span>b</span>
  </div>
  <div ng-repeat="ex in example.arr">
    <span>a</span>
    <span>b</span>
  </div>

</div>

How can you modify the ng-repeat to achieve this output:

<div ng-controller="ExampleController as example" >      

  <section> <!-- wrap each set of (x) ng-repeated elements within a section -->

    <div ng-repeat="ex in example.arr">
      <span>a</span>
      <span>b</span>
    </div>
    <div ng-repeat="ex in example.arr">
      <span>a</span>
      <span>b</span>
    </div>

  </section>

  <section>

    <div ng-repeat="ex in example.arr">
      <span>a</span>
      <span>b</span>
    </div>
    <div ng-repeat="ex in example.arr">
      <span>a</span>
      <span>b</span>
    </div>

  </section>

</div>

Answer №1

If you want to group data in a specific way, one approach is to create a new array with the desired grouping and utilize two ng-repeat directives:

$scope.data2 = (function(data, count) {
    var arr = [];
    var len = data.length / count;
    for (var i=0 ; i<len ; i++) {
        arr.push(data.slice(i*count, (i+1)*count));
    }
    return arr;
})($scope.data, 3);

-

<section ng-repeat="group in data2">
  <div ng-repeat="item in group">
    <span>{{item.a}}</span>
    <span>{{item.b}}</span>
  </div>
</section>

In this setup, data represents the initial array, while count specifies the number of items in each group.
You can view the implementation on this fiddle: http://jsfiddle.net/a9n1e7w5/2/

While there may be alternative methods to achieve this, the provided solution effectively accomplishes the task.

Answer №2

This is practically identical to Austin's version, just presented more eloquently.

http://jsfiddle.net/u4e7dcgv/

<main id="main" class="content column" role="main" ng-controller="GalleryController as gallery">
   <div ng-repeat="row in gallery.rows" class="content row">
    <article ng-repeat="gal in row"  class="post">
        <div class="post-content">{{gal.p}}</div>
    </article>
  </div>
</main>


/**
 * Divides an array of elements into smaller arrays within the element.
 * @param   {Array}  - arrayOfItems
 * @param   {Number} - numberOfRows (default is 4)
 * @returns {Array}
 */
function wrapIntoRows(arrayOfItems, numberOfRows) {
    var items = arrayOfItems,
        rows = numberOfRows || 4,
        wrappedDom = [];

    function wrap(arr, num) {
        var surround, notSurrounded, _num = num;

        if (arr.length > _num) {
            surround = arr.slice(0, _num);
            notSurrounded = arr.slice(_num, arr.length);

            wrappedDom.push(surround);
            // loop
            wrap(notSurrounded, _num);
        } else {
            var remainder = _num - arr.length;
            surround = arr;

            for (var i = 0; i < remainder; i++) {
                var emptydiv = document.createElement('div');
                surround.push({});
            }
            wrappedDom.push(surround);
        }
    }

    wrap(items, rows);
    return wrappedDom;
}

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

Gallery.controller('GalleryController', function ($scope) {
    var gallery = this,
        ArrayOfData = [
              { p: "value 1" }
            , { p: "value 2" }
            , { p: "value 3"}
            , { p: "value 4"}
            , { p: "value 5"}
            , { p: "value 6"}
        ];
    gallery.rows = wrapIntoRows(ArrayOfData);
    $scope.GalleryController = this;
    return $scope.CompanyController;
});

angular.bootstrap(document.body, [
    "Gallery"
 ]);

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

Error: The function user.comparePassword does not exist or is not defined

I am facing an error that says TypeError: user.comparePassword is not a function. I have ensured that all dependencies are installed and the APP is linked to all the libraries. I tried using Postman to retrieve data, but it doesn't seem to be workin ...

Tips for preventing circular dependencies in JavaScript/TypeScript

How can one effectively avoid circular dependencies? This issue has been encountered in JavaScript, but it can also arise in other programming languages. For instance, there is a module called translationService.ts where upon changing the locale, settings ...

Integrating Amazon external images in NextJS

There is a specific issue with loading images from a URL stored on Amazon S3 within the domain configured in next.config.js. Strangely, when using external URLs like Unsplash, the images load fine. The problematic URL is: idinheiro-admin-images.s3.sa-east ...

The installation of the Java package via npm failed with the error message: "Unable to access include file: 'jni.h'. File or directory not found."

Encountering issues with the npm install java command in Windows cmd. The 'jni.h' file is located in the INCLUDE variable within the Windows Environment Variables at C:\Program Files\Java\jdk-15.0.2\include. Include variable ...

Unable to trigger onclick event for creating a new title

I'm currently working on a text generator project using JavaScript. My goal is to create a function that saves the selected text from a dropdown menu and displays it as the page title when the "Generate" button is clicked. The issue I'm facing i ...

A more efficient method for creating a nested array of distinct values using JavaScript

The scenario: My website has a complex html table structure to showcase hierarchical data, with the ability for users to toggle visibility of individual rows. Each row is identified by a dom id consisting of a level number and primary key specific to that ...

Issue with React.js: The formData is empty when trying to add a value from a file using material-ui-dropzone

I am currently working on integrating an upload feature using a library named material-ui-dropzone Although I believe the file upload process is functioning correctly, I encounter an issue with axios where the formData appears empty even prior to sending ...

What is the process for establishing a reference to a property of an object in JavaScript?

Imagine you have an object structured like this: obj = {a:{aa:1}, b:2}; You decide to create a convenient variable (referred to as a pointer) named x that points to obj.a.aa with the following code: x = obj.a.aa; Next, your goal is to update the value ...

I require limitless onclick functionality, but unfortunately, transitions are not functioning as expected

I'm currently working on creating a dynamic photo gallery, but I've encountered a couple of issues that need to be addressed... The "onclick" function in my JavaScript only allows for a single click, whereas I need it to be able to handle mul ...

Exploring the Printing Options in Opera using ASP.NET

When using JavaScript, I encountered an issue where the print dialog box would not appear. The new window would open successfully, but the print dialog was missing. This problem only occurred in Opera, while IE, Chrome, and Mozilla worked fine. I have rese ...

Utilizing async/await in React Redux for geolocation functionality

While attempting to retrieve the lng and lat by using geolocation with async and await, I encountered a situation where the promise was not awaited before it was passed to the reducer. Instead, another promise was returned. I had hoped that by using await ...

Display the LOADING indicator until the entire page has finished loading

Here is the JavaScript code that I am currently using: function generateRequest(){ var request; if(window.XMLHttpRequest){ // Works with Firefox, Safari, Opera request = new XMLHttpRequest(); } else if(window.ActiveXObject) ...

Child component in VueJs is undergoing a situation where the variable is found to be

Whenever an event is triggered, a function is called to populate a variable and open a modal from a child component. However, in the modal, the new variable appears empty initially. If I close and then reopen the modal, the data finally loads. I have atte ...

Steps to access arrays that are embedded in a file and are loaded asynchronously

https://gyazo.com/e80eea9f69c0cbb52cc7929d0a46ea2f The name of the object is totalCount. How can I retrieve the count from it? Object.result was my first attempt, but it returned undefined. For my second attempt: var count = totalCount.resu ...

Mastering the art of dynamically chaining methods in JavaScript

I am in search of a method to dynamically chain different populate methods for various paths in a Mongoose document. The goal is to efficiently retrieve all necessary fields at once. Below is the current code snippet: let fields = [path1, path2, ...] let ...

JasmineJS: manipulating the DOM to achieve the desired outcome

Currently, I am in the process of writing unit tests for a function that requires fetching values from the DOM for processing. getProducts: function() { //Creating query data var queryData = {}; var location = this.$('#location').val(); ...

Executing a Javascript button click in Selenium without an ID using Java

Currently, I am in the process of setting up a Java program integrated with Selenium automation tool. Upon the initiation of the program, a Chrome extension that is crucial for its functionality loads alongside the Chrome browser instance. Following this ...

Can sound be triggered from a JS file within Django's HTML template without using Ajax?

I'm currently in the process of transitioning a website to utilize the Django framework. Most of the JS scripts are functioning properly, except for those that involve sound. Specifically, I have a play/pause button for a song and some sounds that sh ...

What is the best way to update my real-time search results by clicking on the clear button inside the search input field using JavaScript?

I’ve been working on implementing a live search feature. I managed to create live search using ajax, so it displays results that match the alphabet or word I type in. However, I encountered an issue with the cross button inside the search field. When cli ...

Retrieve the ActiveTabIndex value from an Ajax TabContainer using Javascript

Is there a way to retrieve the ActiveTabIndex from TabContainer when a tab is selected by the user? I've attempted the following approach without success. <script type="text/javascript"> function GetActiveTabIndex() { var tc = docum ...