Creating tables using ng-repeat in AngularJS and Bootstrap

Although I am new to Angular, I have been struggling with a problem for the past few days and can't seem to find a solution.

I want to create a matrix of images (charts generated by angular-chart module) with 2 columns that will dynamically load a variable number of images. My aim is to achieve something like this:

image

After some attempts, I came up with the following code snippet:

<div ng-repeat="item in items">
    <div class="row">
        <div class="col-lg-6">
            <div class="panel panel-primary">
                <div class="panel-heading">
                    <h3 class="panel-title">{{ item.name }}</h3>
                </div>
                <div class="panel-body">
                    {{ item.data }}
                </div>
            </div>
        </div>

        <div class="col-lg-6" ng-init="$index = $index + 1">
            <div class="panel panel-primary">
                <div class="panel-heading">
                    <h3 class="panel-title">{{ item.name }}</h3>
                </div>
                <div class="panel-body">
                    {{ item.data }}
                </div>
            </div>
        </div>
    </div>
</div>

However, I encountered an issue where modifying the value of the $index variable within ng-repeat seemed impossible. How can I overcome this obstacle and successfully build a dynamic matrix of images based on data stored in an array of objects?

Answer №1

It seems like you are on the right track. Here is a suggested code snippet for your Controller:

$scope.items = [{name:'name', data:'Image1'}, 
      {name:'A', data:'Image2'},
      {name:'B', data:'Image3}, 
      {name:'C', data:'Image4'},
      {name:'D', data:'Image4'}, 
      {name:'E', data:'Image5'}];

For your HTML, you can use the following:

<div ng-repeat="item in items">
        <div class="col-lg-6">
            <div class="panel panel-primary">
                <div class="panel-heading">
                    <h3 class="panel-title">{{ item.name }}</h3>
                </div>
                <div class="panel-body">
                    {{ item.data }}
                </div>
            </div>
        </div>
</div>

Answer №2

var app = angular.module('main', []);
app.controller('DemoCtrl', function ($scope) {
 
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>

    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" />


<div ng-controller="DemoCtrl" ng-app="main">  

  
  <div ng-repeat="i in [1, 2, 3, 4,5,6,7,8,9,10,11,12]" style="float:left;" >
    <div class="row"  style='padding:10px; '>
        <div class="col-lg-2" style='padding:10px;'>
            <div class="panel panel-primary" style='width:200px' >
                <div class="panel-heading">
                    <h3 class="panel-title">{{i}}</h3>
                </div>
                <div class="panel-body">
                   {{i}}
                </div>
            </div>           
        </div>      
    </div>
  </div>  
</div>

Answer №3

      <!--Remember to modify this code as follows: -->
      <div class="row">
     <div ng-repeat="element in elements" ng-include="'content.html'">
     </div>

      <!-- Also, ensure that file content.html is located in the same directory and contains the following content: -->

    <div class="col-lg-6">
       <div class="panel panel-primary">
           <div class="panel-heading">
             <h3 class="panel-title">{{ element.title }}</h3>
           </div>
        <div class="panel-body">
                {{ element.content }}

     </div>
     </div>
   </div>

Answer №4

After much persistence, I successfully tackled this issue by iterating through various index variables to extract the correct elements, as illustrated in the example below.

<div ng-repeat="i in [] | range:10 ">
    <div class="row">
        <div class="col-lg-6">
            <div class="panel panel-primary">
                <div class="panel-heading">
                    <h3 class="panel-title">{{ items[i].name }}</h3>
                </div>
                <div class="panel-body">
                    items[i].value
                </div>
            </div>
        </div>

        <div class="col-lg-6">
            <div class="panel panel-primary">
                <div class="panel-heading">
                    <h3 class="panel-title">{{ items[i+1].name }}</h3>
                </div>
                <div class="panel-body">
                    items[i+1].value
                </div>
            </div>
        </div>
    </div>
</div>

Additionally, a filter was implemented in JavaScript:

myApp.filter('range', function() {
    return function(input, total) {
        total = parseInt(total);

        for (var i=0; i<total; i=i+2) {
          input.push(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

Sending information to varying view/module - AngularJS

I am relatively new to AngularJS, so my question may seem quite basic. In one of my views, I have a link that, when clicked, calls a service to retrieve data. In the controller, I am using $location to change the view and update it with the data fetched f ...

Implementing the useEffect hook in React to iterate over JSON data and update the state

Having trouble implementing job location filtering ("remote"/"in-person"/"hybrid") for my personal project. As a beginner in programming, I've spent quite some time troubleshooting the fetchLocationData function and passing URLSearchParams. I anticipa ...

Words of wisdom shared on social media

How can I share text from my HTML page on Twitter? This is the code snippet from my HTML page - function change() { quotes = ["Naam toh suna hi hoga", "Mogambo Khush Hua", "Kitne aadmi the?"]; auth = ["Raj", "Mogambo", "Gabbar"]; min = 0; max = ...

Enter key always causes the Bootstrap form to submit

I am working with a jquery function: $("#get-input").keyup(function (event) { if (event.keyCode === 13) { $("#get-data").click(); } }); $("#get-data").click(function (e) { var endpoint = $(".get-input").val(); if ($('#data-d ...

Accessing the $index value from the selected option when using ng-change within a select element

Although there are similar questions out there, I couldn't find one that addresses my specific need: ngRepeat inside option-tag ngChange inside select-tag I am trying to retrieve the index of the selected option. Here is a snippet of my code: < ...

Is there a way for me to collaborate on a footer control with a different website?

Is it possible to seamlessly incorporate a footer from one website into another? Ideally, I want the footer HTML (and styles) to be dynamically inserted into different web pages. The common workaround is using an iframe, but this causes navigation issues ...

Tips for testing a mapbox popup using jasmine testing?

I encountered an issue with my mapbox popup while using jasmine and attempting to write a unit test for it. Here is the function in question: selectCluster(event: MouseEvent, feature: any) { event.stopPropagation(); this.selectedCluster = {geo ...

show a pie chart at the top of the div using highcharts

i am struggling with positioning the high-chart with a label, as seen in the image below https://i.sstatic.net/m9bXW.png does anyone know how to properly display the chart from the top left corner? i have attempted to adjust the settings like this { ...

Organize data that is deeply nested

Struggling to normalize deeply nested API response data? Look no further than https://github.com/paularmstrong/normalizr. This tool can help simplify your data structure. For example, if your input data looks like this: const data = [{ id: 'compone ...

Learn how to hide a bar after clicking the "I agree" button with the help of Bootstrap

click here to see imageIs there a way to make that bar disappear once the user clicks "I agree"? I've searched through Bootstrap documentation but couldn't find a solution. Please assist. Below is the code snippet: <div id="cookie-message" cl ...

Enhance global variable by appending a line from a local function in Javascript

In my js files, I have some global functions that are used in all modules of the application. Currently, I am working on a module that requires modifying one of these global functions to run a local script every time it is called. The issue is that the g ...

The NextJs router encountered an unknown key passed through the urlObject during the push operation

I have a Next.js/React application where I am utilizing the Next Router to include some queries in my URL. However, when using the following function, the Chrome Dev Console displays numerous warnings: const putTargetsToQueryParams = (targets: IFragrance ...

Find the name of the region in the user's query

I've implemented the weather-js npm module (weather-js) to retrieve weather information for a specific region. While everything is functioning correctly, I'm looking to customize it based on user input. The module currently only accepts region ...

Running JavaScript function from AJAX response containing both HTML and JavaScript code

For my first time using AJAX to prevent page refresh upon form submission, everything works flawlessly. The data is received in HTML form and placed into the designated div. However, I am encountering an issue with one of the JavaScript functions responsib ...

Rails - implementing ajax in partials causing an error: 'cannot find method render'

I am encountering an issue with my form partial located within a div that has the id "chapcomments". The form includes a submit button: <%= f.submit "Post", remote: true %> Within the correct view folder, I have a file named create.js.erb which con ...

The error message indicates that the Worklight adapter is an object, not a function

Upon deploying the Worklight adapter to the production server, I encountered an error when the adapter called a Java code from JavaScript: Procedure invocation error. Ecma Error: TypeError: Cannot call property updateProposal in object [JavaPackage com.id ...

What is the preferred method for logging out: using window.location.replace('/') or setting window.location.href to window.location.origin?

When it comes to a logout button, which is the better option: window.location.replace('/') or window.location.href=window.location.origin? Can you explain the difference between these two methods? It's my understanding that both of them remo ...

Utilizing highlight.js for seamless integration with vue2-editor (Quill)

I am having trouble connecting vue2-editor (based on quill) with highlight.js Despite my efforts, I keep encountering an error message that reads: Syntax module requires highlight.js. Please include the library on the page before Quill. I am using nu ...

Steps for generating an HTML button when an Angular function evaluates to true

I am working on a table in HTML that uses ng-repeat to display data. Here is the code snippet for this table: <tbody> <tr dir-paginate="x in serverData | filter:filterData | filter:filterData | itemsPerPage: itemPerPageValue | order ...

Storing JavaScript object in a database using a PHP script

My current scenario involves having a JavaScript object which can be converted into JSON format using the stringify method. Here's how it looks: var jsObject ={'elem1':'val1', 'elem2': {'elem21':'val1&apos ...