Navigating variable columns and rows in a static column table

Here is a preview of how my table will appear:

<table>
<thead>
    <tr>
        <th>Name</th>
        <th>Week 1</th>
        <th>Week 2</th>
        <th>Week 3</th>
    </tr>    
</thead>
<tbody>
    <tr>
        <td>Cooper</td>
        <td>Vikings</td>
        <td>Giants</td>
        <td>Rams</td>
    </tr>
    <tr>
        <td>Jon Doe</td>
        <td>Bears</td>
        <td></td> 
        <td>Seahawks</td>
    </tr>
</tbody>

Below is an example of the data I will be working with:

{
 "name" : "Cooper",
 "picks" [{"w1": "vikings"}, {"w2" : "Giants"}, {"w3" : "Rams"}]
},
{
 "name" : "Jon Doe",
 "picks" [{"w1": "Bears"}, {"w3" : "Seahawks"}]
}

I am seeking recommendations on the best approach to generate my output. While this is a basic illustration, in reality, my model will include 30 columns and some may be hidden depending on the week. The picks will follow a specific order, however, there might not be selections for every week. As shown in my example, Jon Doe did not choose a team for Week 2.

Thank you!

Answer №1

To optimize your data structure, consider transitioning from an array to an object with keys for each week. This eliminates the need for inserting dummy or undefined records in the array, although that approach isn't necessarily problematic.

Below is a snippet showcasing a directive that can effectively address your issue. Note the specification of max-columns as 3 in the html for the directive (the tbody element).

angular.module("app", [])
  .controller("pickersCtrl", ['$scope',
    function($scope) {
      $scope.data = [{
        "name": "Cooper",
        "picks": {
          "w1": "Vikings",
          "w2": "Giants",
          "w3": "Rams"
        }
      }, {
        "name": "Jon Doe",
        "picks": {
          "w1": "Bears",
          "w3": "Seahawks"
        }
      }];
    }
  ])
  .directive("pickersRepeat", [
    function() {
      return {
        restrict: 'EA',
        scope: {
          pickers: '=',
          maxColumns: '@'
        },
        link: function(scope, element, attrs) {
          scope.$watch("pickers", function(pickers) {
            if (!pickers) {
              return;
            }
            var maxColumns = +scope.maxColumns;
            for (var i = 0; i < pickers.length; i++) {
              var picker = pickers[i];
              var row = angular.element('<tr/>');
              element.append(row);
              var nameColumn = angular.element('<td/>').text(picker.name); // append user name to Entry row
              row.append(nameColumn);
              var picks = picker.picks; // get user picks
              
              for (var j = 0; j < maxColumns; j++) {
                var column = angular.element('<td/>');
                row.append(column);
                var pick = picks["w" + (j + 1)]; // since the wX seem to start with 1 instead of 0 we add 1 here
                if (pick) {
                  // user made a pick for week j
                  column.text(pick); // put the text in column j
                }
              }
            }
          });
        }
      };
    }
  ]);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app">
  <table ng-controller="pickersCtrl">
    <thead>
      <tr>
        <th>Entry</th>
        <th>1</th>
        <th>2</th>
        <th>3</th>
      </tr>
    </thead>
    <tbody pickers-repeat pickers="data" , max-columns="3">
    </tbody>
  </table>
</div>

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

Encountered an unexpected runtime error in Next.js - TypeError: Unable to access properties of null object (specifically 'tagName')

25 | const tagsList = []; 26 | for(let count = 0, index = headerEl.previousElementSibling; count < totalTags; count++, index = index.previousElementSibling){ > 27 | if (index.tagName.toLowerCase() === elementType) { | ...

Attaching a click event to a nested element within an AngularJS directive

I am currently working with the following directive. (function () { 'use strict'; angular.module('ap.App') .directive('clearCancelFinishButtonsHtml', function () { return { scope: { ...

Issues arising from using `track by $index` in Angular UI Carousel

Issue with index starting at non-zero value when using pagination in Angular UI Bootstrap carousel I've implemented a carousel using Angular UI Bootstrap to display a large number of images (over 1,000). To improve performance, I added a filter to sh ...

Utilizing JSON and select for dependency management

Let's say we have a JSON object: { "A": { "1": "1", "2": "2", "3": "3" }, "B": { "4": "4", "5": "5", "6": "6" }, "C": { "7": "7", "8": "8" } } And we also have ...

Understanding the functionality of scope in AngularJS is essential for mastering the framework

Why does this code work? app.controller("ctrl", function($scope){ $scope.From = "Santa"; $scope.To = "Claus"; }); And why doesn't this one work? app.controller("ctrl", function(scope){ scope.From = "Santa"; scope.To = "Claus"; }); ...

Obtain the parameter of a parent function that runs asynchronously

Here's the code snippet I'm working with: function modify( event, document ) { console.log( "document name", document ); //I need it to be 'file', not 'document'. documents.clients( document, function( clientOfDocument ...

Unable to resolve the issue within Angular UI modal

Currently, I am facing an issue with displaying a modal using Angular Bootstrap UI. The modal is supposed to resolve items in the controller, but I am struggling to access those resolved items in the modal controller. $scope.showItemsInBill = function(bill ...

Ways to bypass browser pop-up blockers when using the window.open function

I am displaying an HTML retrieved from the backend. printHtml(htmlContent) { var windowToPrint = window.open('', '_blank'); windowToPrint.document.write(htmlContent); setTimeout(function () { windowToPrint.document ...

Exploring Javascript through Python using Selenium WebDriver

I am currently attempting to extract the advertisements from Ask.com, which are displayed within an iframe generated by a JavaScript script hosted by Google. Upon manually navigating and inspecting the source code, I can identify the specific element I&ap ...

Updating Sencha list itemTpl on the fly

Is there a way to dynamically change the itemTpl in a Sencha list to adjust the visibility of a column based on certain conditions? Your assistance would be greatly appreciated. ...

Styling the <Autocomplete/> component in Material UI with React to achieve rounded corners

Google's search bar has always been a favorite of mine, with its rounded corners and generous text padding. https://i.stack.imgur.com/UbKrr.png I'm attempting to replicate this aesthetic using Material UI's <Autocomplete/> component ...

Choosing the appropriate data type for form data on the server

Seeking assistance on uploading an audio file to my server using the following method: var fd = new FormData(); fd.append('fname', 'test.wav'); fd.append('data', soundBlob); $.ajax({ type: 'POST', url: &apos ...

Encountering a problem with the Ionic Modal Slider: unable to locate the matching element associated with delegate-handle= when using $

I am encountering a problem with my Ionic application that features multiple Angular controllers. Specifically, I have a LoginCtrl and RegisterCtrl controller set up. The issue arises when I try to trigger a modal with a slider from the RegisterCtrl by usi ...

Can you guide me on creating a post and get request using ReactJS, Axios, and Mailchimp?

I am brand new to ReactJS and I am currently working on developing an app that requires integration with Mailchimp to allow users to subscribe to a newsletter. I am looking for assistance on making a request using axios. Where should I input my API key? ...

Node and Express Fundamentals: Delivering Static Resources

const express = require('express'); const app = express(); app.use(express.static('public')); I've been attempting to complete the "Basic Node and Express: Serve Static Assets" challenge on freecodecamp, but it keeps showing as " ...

How can I automate testing with Cucumber using Rails and Capybara to manage an AngularJS dialog box?

Currently, I am developing an application that utilizes AngularJS. There is a flow in the application where clicking a button triggers a dialog box to appear with various fields. I am facing an issue when trying to input values into the fields within the ...

Challenges with 'this' reference in a requireif causing Vuelidate complications

     Need help with vuejs component using vuelidate and validations:     validations: {      invoice: {          dueDate: {              required,          },          tax: {              require ...

"Mastering the art of utilizing Async in combination with waterfall and Recursion in node

I've developed a script for transferring data from Dynamo to a MySQL database. Initially, I encountered performance issues on the SQL side due to not using asynchronous calls. To address this, I integrated the async library to throttle the Dynamo segm ...

What is the best way to create a dynamic pie chart in AngularJS using JSON data?

In my controller: When calling the web services, if the service is successful, then retrieve the data and push it into the corresponding arrays. for(var i = 0; i < $scope.reportRangeList.length; i++) { count++; if( ...

Having trouble retrieving the $_SESSION variable accurately from AngularJS

I am working with angularjs and need to retrieve a php session variable. I have created a php file named session.php with the following content: $_SESSION['phone'] = '55551864'; return json_encode($_SESSION['phone']); In my ...