Creating a complex HTML structure by utilizing nested ng-Repeat loops

Transforming my HTML to Angular with ng-repeat. Currently displaying 9 items, 3 max per row. Code snippet:

<div class="row clearfix">
    <div class="btn-group btn-group-justified btn-group-lg">
       <div class="btn-group">
            <button type="button" class="btn btn-xlarge btn-primary-items" data-price="1.05">Item 1</button>
       </div>
       <div class="btn-group">
            <button type="button" class="btn btn-xlarge btn-primary-items" data-price="2.05">Item 2</button>
       </div>
       <div class="btn-group">
            <button type="button" class="btn btn-xlarge btn-primary-items" data-price="2.55">Item 3</button>
       </div>
    </div>
</div>
...

Looking to replicate this structure in Angular. JSON payload example:

items = [
     { name: "item1", price: "1.05" },
     { name: "item2", price: "2.05" },
     ...
];

Answer №1

If you want to ensure that your JSON response is correctly structured for the angular directive, you may need to reformat it or preprocess it before passing it on.

var itemRows = [
 [{ name: "item1", price: "1.05" },
 { name: "item2", price: "2.05" },
 { name: "item3", price: "2.55" }],
 [{ name: "item4", price: "2.65" },
 { name: "item5", price: "3.05" },
 { name: "item6", price: "4.95" }],
 [{ name: "item7", price: "4.15" },
 { name: "item8", price: "1.15" },
 { name: "item9", price: "1.95" }]
];

Make sure to pass itemRows as the object to be displayed in the template instead of individual items.

If changing the backend is not feasible, pre-processing the data is recommended following this approach:

In Javascript:


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

    myApp.controller('ItemRowsCtrl', ['$scope', function($scope) {
      var items = [
        { name: "item1", price: "1.05" },
        { name: "item2", price: "2.05" },
        { name: "item3", price: "2.55" },
        { name: "item4", price: "2.65" },
        { name: "item5", price: "3.05" },
        { name: "item6", price: "4.95" },
        { name: "item7", price: "4.15" },
        { name: "item8", price: "1.15" },
        { name: "item9", price: "1.95" }
      ];
      var itemRows = [];
      for (var i = 0; i < items.length; ++i) {
        if (i % 3 === 0) {
            itemRows.push([]);
        }
        var itemRow = itemRows[itemRows.length - 1];
        itemRow.push(items[i]);
      };  
      $scope.itemRows = itemRows;
    }]);

In your template:


    <body ng-app="myItems">
      <div ng-controller="ItemRowsCtrl">
        <div class="row clearfix" ng-repeat="itemRow in itemRows">
            <div class="btn-group btn-group-justified btn-group-lg">
               <div class="btn-group" ng-repeat="item in itemRow">
                    <button type="button" class="btn btn-xlarge btn-primary-items" data-price="{{item.price}}">{{item.name}}</button>
               </div>
            </div>
        </div>
      </div>
    </body>

JsBin answer

Answer №2

I have attempted to replicate your question in a demo available at http://jsfiddle.net/7eYnt/. Hopefully, this will provide clarity on the ng-repeat concept in your specific case. Thank you.

HTML

 <div class="row clearfix" ng-repeat="item in items">
        <div class="btn-group btn-group-justified btn-group-lg">
   <div class="btn-group">
    <button type="button" class="btn btn-xlarge btn-primary-items" data-price="1.05">{{ item.name }}</button>
          </div>
            </div>
          </div>

JS

function MainController($scope) {
  $scope.items = [
     { name: "item1", price: "1.05" },
     { name: "item2", price: "2.05" },
     { name: "item3", price: "2.55" },
     { name: "item4", price: "2.65" },
     { name: "item5", price: "3.05" },
     { name: "item6", price: "4.95" },
     { name: "item7", price: "4.15" },
     { name: "item8", price: "1.15" },
     { name: "item9", price: "1.95" }
    ];
}

Answer №3

An Easy Example Using CSS

Instead of complicating your controllers, I suggest using CSS to create your "Grid". This approach helps in keeping your controller separate from the design, making it easier to make changes without affecting other components. By adjusting the CSS, you can modify the number of items in the grid without touching the template or controller.

Furthermore, utilizing CSS Media Queries allows you to customize the layout for different devices such as mobile phones.

For this kind of task, I recommend using ul and li HTML elements. Depending on your needs, you may need to add or modify elements accordingly.

Template

<ul class="buttons">
    <li ng-repeat="item in items">
        <button type="button" class="btn btn-xlarge btn-primary-items" data-price="1.05">{{ item.name }}</button>
    </li>
</ul>

Controller

function MainController($scope) {
    $scope.items = [{
        name: "item1",
        price: "1.05"
    }, {
        name: "item2",
        price: "2.05"
    }, {
        name: "item3",
        price: "2.55"
    }, {
        name: "item4",
        price: "2.65"
    }, {
        name: "item5",
        price: "3.05"
    }, {
        name: "item6",
        price: "4.95"
    }, {
        name: "item7",
        price: "4.15"
    }, {
        name: "item8",
        price: "1.15"
    }, {
        name: "item9",
        price: "1.95"
    }];
}

CSS

ul.buttons {
    list-style-type:none;
}

ul.buttons li {
    padding: 5px;
    width:30%;
    display:inline-block;
    vertical-align:top;
    text-align:center;
}

Check out the Demo

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

Images are failing to load in Ionic 3

Currently working on developing an Ionic application and troubleshooting the use of the camera native plugin. The script functions flawlessly in a fresh project, but encounters issues within the current project environment. Initially suspected a problem w ...

Using the "i" parameter in a Lodash for loop results in undefined, however, it functions properly with specific values set

My goal is to use Lodash to search for specific integer values in an object and then store some of those values in an array. The integers are variable and come from a separate array, but I am consistently getting undefined as the result. If I manually inp ...

When I use Input.value, it seems to cause a strange lag in my console.log

My goal is to have a text input on the page that triggers #fourChord's text to change as I type characters into the input. The issue I am facing is that console.log registers my input, but the first character is always ignored. For example, if I type ...

Need help with writing code in Angular for setting intervals and clearing intervals?

I am working on the functionality to display a loader gif and data accordingly in Angular. I have tried using plain JavaScript setInterval code but it doesn't work for $scope.showLoader=true and $scope.showResult=true. The console.log('found the ...

I am encountering problems with images that are imported as module imports in a Vue.js project

Currently, I have stored all the default images for my Vue project in a designated folder. The path to this folder is web/images/defaults/<imageNames>.png. Instead of importing each image individually in my components, I wish to create a file that co ...

Error: The property 'match' is undefined and cannot be read by Object.j during rendering in angular-datatables.min.js at line 6

I am currently using angular-datatables.min.js for my data table, but I have encountered an error that I have been unable to resolve. Is there anyone who can provide assistance with this issue? App.controller('DailyTaskListController', ['$s ...

When the value is blank, do not include the class attribute when appending

http://jsbin.com/guvixara/1/edit I have a situation where I am dynamically inserting a button... $(".confirm-add-button").on("click", function() { var $ctrl = $('<button/>').attr({ class: $('.newbtnclassname').val()}).html($(& ...

Determine whether a specific text is contained within a given string

Can someone help me determine if a specific text is included in a string? For example, I have a string str = "car, bicycle, bus" and another string str2 = "car" I need to verify if str2 exists within str. I'm new to JavaScript so I appreciate you ...

Using the JQuery template with $.get function does not produce the desired result

Working on populating a table using a Jquery Template can be tricky. One challenge is incorporating a json file via an ajax call for the population process. $(document).ready(function() { var clientData; $.get("/webpro/webcad/lngetusuario", funct ...

Exploring the method to search across various fields in Vue.js 2

In my Vue.js 2 application, I am attempting to search or filter through three fields: firstname, lastname, and email. Unlike Vue 1, Vue 2 does not include a built-in filter method. As a result, I have created a custom method that can only filter through on ...

Error with NextJS and styled-components in the bundle file

I recently integrated styled-components into my React project. However, when I bundled the react application using rollupjs and tried to use this bundle with NextJS, I encountered an error in NextJS: ReferenceError: window is not defined Upon inspecting t ...

Include a message for when there are no results found in the table filter

I am currently working with a code that filters a table, but when there are no results, the table appears blank. Can someone assist me in adding a "No results found" message to display when nothing is found? $(document).ready(function() { $("#table_s ...

Having Trouble Importing a Dependency in TypeScript

My experience with using node js and typescript is limited. I attempted to include the Paytm dependency by executing the following code: npm install paytmchecksum or by inserting the following code in package.json "dependencies": { ... & ...

Guide on generating a POST request with CSRF token integration in Django and AngularJS

I'm attempting to make a POST request using angular.js to communicate with this Django view. class PostJSON4SlickGrid(View): """ REST POST Interface for SlickGrid to update workpackages """ def post(self, request, root_id, wp_id, **k ...

How to toggle tooltip visibility dynamically using Angular 2

I am working with elements within an ngFor loop. Some of these elements have tooltips, while others do not. I am experiencing an issue where when using the code snippet below: <div ngFor="let item of items"> <div [title]="item.title"> Ele ...

"Rotating the TransformControl in threejs: A step-by-step guide

When the object attached to the transform control rotates, I want the transform control itself to rotate as well. Before the rotation: https://i.sstatic.net/yjTue.png After the rotation: https://i.sstatic.net/2opuU.png As shown in the image, before th ...

Loop through a nested array of objects within the same row using ng-repeat

Struggling with binding data from a nested array in the same row. Here is my Array of Objects: $scope.Record = [ { Name:'Adam', Months:[ {Month: 'Jan', Value: 10, cust:2}, {Month: 'Feb', Value: 30, cust:2} {Month: 'M ...

Tips for Enhancing JavaScript Performance

Is there a way to enhance my JavaScript code like this: $(window).scroll(function() { if ($('#sec1').isVisible()) { $('.js-nav a.m1').addClass('active'); } else { $('.js-nav a.m1').removeClas ...

JavaScript consistently returns HiddenField as NULL

After creating a Context menu and associating it with a Gridview, I noticed a problem when pressing a button from the context menu. I intended to retrieve a value from a HiddenField, but it always returns null. My assumption is that the DOM might not be fu ...

Obtaining NodeJS from a mysterious subdirectory

-- plugins ---- myplugin1 ------ core ---- myplugin2 ------ core If this represents the directory structure, is there a method to import all core directories from plugins without specifying the specific plugin names like myplugin1? require('/plugins ...