Create an AngularJS Directive that will display an array of n elements in the form of m rows of tables

Challenge: I have an array of 'n' items that I need to display in separate tables, with each table containing m rows. For instance, if n=30 and m=6, then I should have 5 tables each with 6 items displayed horizontally.

Proposed Solution: I attempted to use ng-repeat and ng-switch to achieve this layout, but encountered issues. While I can easily render the items in a single table, splitting them into multiple tables as described has proven tricky.

I am aware that the code snippet provided below is incorrect due to the unclosed ng-switch tags. Are there any common approaches or tricks to accomplish this kind of layout?


itemapp.directive("items", function () {
    'use strict';

    return {
        restrict: 'E',
        template: '<div id="itemDiv" ng-repeat="item in items" ng-show="$index==0">' +
            '<span ng-switch on="$index % 10">' +
            '   <div ng-switch-when="0">' +
            '           <table><tbody>'+
            '   </div>'+
            '<tr class="itemon">' +
            '<td><input type="radio" ng-model="item.on" value="0" >OFF</input></td>' +
            '<td>{{$index}}</td>'+
            '</tr>' +
            '   <div ng-switch-when="9">' +
            '    </table></tbody>'+
            '   </div>'+
            '</span>' +
            '</div  ng-show="$index==0">',
        link: function (scope) {

        },
        scope: {
            items: '='
        }
    };
});

Below is the HTML Template version of the code:

<div id="itemDiv" ng-repeat="item in items" ng-show="$index==0">
 <span ng-switch on="$index % 10">
<div ng-switch-when="0">
    <table>
        <tbody>
</div>
           <tr class="itemon">
               <td><input type="radio" ng-model="item.on" value="0">OFF</input></td>
               <td>{{$index}}</td>
            </tr>
      <div ng-switch-when="9">
          </table></tbody>
      </div>
</span>
</div  ng-show="$index==0">

Answer №1

Here is my solution:

Custom directive:

<table ng-repeat='t in getIndexes(tableCount) track by $index'>
  <tbody>
    <tr ng-repeat='item in items' ng-if='isVisible($parent.$index,$index)'>
      <td>{{item.name}}</td>
      <td>{{item.city}}</td>
    </tr>
  </tbody>
</table>

getIndexes - a function that creates an array for ng-repeat to iterate through.

isVisible - a function that determines the visibility of each row based on its position in the source array.

Custom directive code:

app.directive("tconstructor", function () {
    'use strict';

    return {
        restrict: 'AE',
        templateUrl: 'directive.html',
        scope: {
            items: '=',
            perTable: '=' // items per table
        },
        link: function ($scope, $element, attrs) {
              $scope.tableCount = $scope.items.length / $scope.perTable;
              $scope.getIndexes = function(count) {
                return new Array(count);
              },

              $scope.isVisible = function(t,i) {
                console.log(t,i,(t*$scope.perTable <= i), (i < (t+1)*$scope.perTable) );
                return (t*$scope.perTable <= i) && (i < (t+1)*$scope.perTable);
              }
        }

    };
});

Index page:

 <div ng-controller="SimpleController">
  <tconstructor items='items' per-Table='perTable'></tconstructor>
 </div>

Live demo: I have set the items array to have 8 elements, and each table contains 2 elements, resulting in 4 tables with 2 items each.

http://plnkr.co/edit/eUM7UJap3VIYviY795UpNVCWsx52u5PvtyeTOLIMsISwtHTbtoahikLNoF3VmkkHReGqykopdkCner3p22liXzQ==

You can easily adjust the code to suit your needs. I hope this helps!

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 are the best methods for profiling a Node.js application at a specific point in its execution?

I am currently facing performance issues with my Node application, which listens to a websocket data feed and communicates with another API. The CPU usage is normally stable at around 2-5%, but occasionally (approximately 3 times within 24 hours) the incom ...

Can we modify the styling of elements in Angular based on an object property?

I have a class named Task with the following properties: export class Task { name: string; state: number; } Within my component.ts file, I have an array of objects consisting of instances of the Task class (tasks). When displaying them in the tem ...

Creating Unique Numbers for Every <a> Element

Can someone help me figure out how to create a form that generates a unique set of random numbers from the range (0,9) displayed in a group of button tags? I've written some javascript code but it's not quite working as intended. (function($) ...

Decoding route parameters in AngularJS version 1.0.7

In my app.js, I have a rule that looks like this: $routeProvider.when('/:language/rental-:type-:departure', {templateUrl: 'partials/rental.html', controller: 'itemCtrl'}); If a user enters a URL such as: /en/rental-houses-sa ...

The Angular JS demo is failing to run. The error message "Argument 'UserCtrl as uCtrl' is not a function, got undefined" is displayed

After watching a tutorial on http://www.youtube.com/watch?v=HCR7i5F5L8c#t=587, I decided to try out the example myself. I added AngularJS 1.0.8 but encountered an error: Argument 'UserCtrl as uCtrl' is not a function, got undefined I suspect ...

Retrieve GPS data source details using Angular 2

In my Angular 2 application, I am looking to access the GPS location of the device. While I am aware that I can utilize window.geolocation.watchposition() to receive updates on the GPS position, I need a way to distinguish the source of this information. ...

Interacting with a button using Python Selenium while validating onFocus with JavaScript

I'm currently working on automating webpage navigation with Selenium in Python. My goal is to click on an HTML button that triggers JavaScript code to validate if the button is focused during the onclick action. Although I can successfully select a v ...

Organize AngularJS ng-repeat using dictionary information

I'm dealing with a dictionary consisting of key-value pairs, which looks something like this: data = { "key1": 1000, "key2": 2000, "key3": 500 } My goal is to display this data in a table using AngularJS. One way I can achieve this is b ...

Utilizing GridFS for efficient file storage in MongoDB with the seamless integration of Mongoose and AngularJS

When I first started, I had very little knowledge on how to save a file to a NoSQL MongoDB using Mongoose and Angular. After extensive research, I discovered that I needed to utilize GridFS to solve my problem. The challenge was finding a detailed explan ...

What could be the reason that step 3 of the AngularJS Tutorial is not functioning correctly?

During Step 3 of the AngularJS Tutorial, an additional e2e test is recommended to enhance the example: it('should display the current filter value within an element with id "status"', function() { expect(element('#status').text() ...

What steps should I take to ensure that the content within a div also goes full screen when I expand the div?

Is there a way to make a flash game go full screen along with its container div? I have a button that expands the div to full screen, but the flash game inside remains stuck in the top left corner of the screen. How can I ensure that the flash game expands ...

Having trouble with Django's submit POST method for creating objects

Latest Updates: I have successfully implemented a feature where the page does not reload upon clicking the submit button. To achieve this, I filled out the form and inspected the page source code. The form structure was as follows: https://i.sstatic.net/ ...

Tips for clearing the input text in an Angular Material form after it has been submitted

<div class="col-md-12 addUsercls"> <div class="col-md-12 add-user-input"> <md-content style="margin: 10px 10px 0px 10px;border-bottom: 1px solid #c9c9c9;"> <md-autocomplete ng-model="ge ...

Implement an event listener on the reference obtained from the React context

Within the React context provider, a ref is established to be utilized by another component for setting a blur event listener. The issue arises when the blur event fails to trigger the listener. The following is a snippet of code from the context provider ...

Show different options like selection menus, checkboxes, date pickers, and more based on the content of a JSON

Looking for Help with Dynamic Input Fields and Additional Elements I have successfully implemented dynamic input fields based on a JSON file, but now I need to include selections, checkboxes, and a datepicker as well according to their respective groups. ...

What is the best way to verify if a class attribute includes a specific class or not?

Below is the code snippet provided. The code fetches all classes and then checks for the presence of the 'mat-checked' class. pmanage.no_additional_cost().last().invoke('prop', 'class').then((Class) => { let ...

Implementing setTimeout with the copy button: A guide

How can I implement a setTimeout function in the copy button so that when a user clicks on it, the text will change to "copied" and then revert back to "copy" after 3-4 seconds? Please help me find a solution to this problem and also optimize the JavaScrip ...

Submit Button Field - HTML ButtonFor

Being relatively new to MVC Razor and web development, both front-end and back-end, I'm in need of a button that can send a stored value to the controller/model. I attempted to mimic the functionality of Html.TextBoxFor by giving it attributes similar ...

Dynamically Add Routes in ExpressJS During Runtime

I am interested in creating routes dynamically at runtime, but I'm not entirely sure how to do it. Currently, I have the following code snippet: var app = express(); function CreateRoute(route){ app.use(route, require('./routes/customchat.js&ap ...

Issue with document.referrer in Firefox: Unexpected behavior

I attempted to utilize the document.referrer function. It functions correctly in Google Chrome, however it does not yield the expected results in Mozilla Firefox. if (document.referrer.indexOf('stringToCheck') > 0) { //insert code here ...