a responsive grid view featuring automatically updated column headings

Can a table be populated in angular.js without predefining column names before the 'ng-repeat'? Currently, the table is populated like this..

                     <table class="table">
                        <thead>
                          <tr>
                            <th>Arup Mnemonic</th>
                            <th>Organism</th>
                            <th>Test</th>
                            <th>Result</th>
                            <th>Source</th>
                            <th>Source Value</th>
                          </tr>
                        </thead>
                        <tbody>
                          <tr ng-repeat="x in data">
                            <td>{{ x.Arup_Mnemonic }}</td>
                            <td>{{ x.organism }}</td>
                            <td>{{ x.test }}</td>
                            <td>{{ x.result }}</td>
                            <td>{{ x.source }}</td>
                            <td>{{ x.source_value }}</td>
                          </tr>
                        </tbody>
                    </table>

Is it possible to eliminate all hard coding and let the scope variable determine the column names and data?

Quick Edit: https://i.sstatic.net/xTfIT.png Here's a quick glance at the data in its current form.. I require the key in the key:value pairs of this object. Is there a way to retrieve those values using pure JavaScript?

Answer №1

It appears that the columns are not known in advance. Therefore, the keys of the first object must be obtained to identify the columns.

angular:

var obj = data[0];
$scope.columns =  Object.keys(obj).filter(function(key) {
  if (obj.hasOwnProperty(key) && typeof key == 'string') {
    return key;
  }
});

$scope.format = function(str) {
    return str.replace('_',' '); //add additional formatting here. 
}

html:

<table class="table">
  <thead>
    <tr>
      <td ng-repeat="column in columns">
        {{format(column)}}
      </td>
    </tr>
  </thead>
  <tbody>
    <tr ng-repeat="datum in data">
      <td ng-repeat="column in columns">
        {{datum[column]}}
      </td>
    </tr>
  </tbody>
</table>

Edit: Adopted the practice of filtering keys from another answer as a best practice for retrieving keys from objects.

Answer №2

Have you considered creating your own model for headlines and iterating through it?

Assume we have an array called headlines which contains all possible headlines, one for each index.

<table class="table">
  <thead>           
    <tr ng-repeat="headline in headlines"> 
      <th>{{ headline }}</th>
    </tr>
  </thead>
  <tbody>
    <tr ng-repeat="x in data">
      <td>{{ x.Arup_Mnemonic }}</td>
      <td>{{ x.organism }}</td>
      <td>{{ x.test }}</td>
      <td>{{ x.result }}</td>
      <td>{{ x.source }}</td>
      <td>{{ x.source_value }}</td>
    </tr>
  </tbody>
</table>

Answer №3

One potential approach to this issue (keep in mind that this code has not been verified):

// within the controller
$scope.titles = Object.keys(data[0]).filter(function(property) {
    if (data[0].hasOwnProperty(property) && typeof property == 'string') {
        return property;
    }
});

Answer №4

   <div data-ng-repeat="(k,v) in dataGrid">
                                <span></span>
                                <span data-ng-repeat="c in cols" data-ng-init="CurrentKey = c.key">{{v[CurrentKey]}}
                                </span>
                            </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

Alter the functionality of the input element that has a tag of 'multiple'

I am encountering an issue with a form that allows users to upload multiple photos. When selecting multiple files at once, everything works as expected. However, if a user wants to add images one by one, each new addition deletes the previous file due to t ...

What steps can be taken to empower users to make changes to pre-selected data within the vue-select component?

Usage of vue-select component: Currently, I am looking for a way to enable my users to edit data that has already been selected. After going through the documentation, I couldn't find a direct method to achieve this. If anyone has experience working ...

The filter feature does not function properly when used with an ng-option generated from an array, but it performs effectively with static

<select ng-model="myOption" class= "form-control" ng-options="value.status for value in records | unique:'status'"> </select> Displays only one record when filtered with the criteria below <tr ng-repeat="data in records | filter: ...

The attempt to update several partial views using Jquery, MVC, and Json is currently malfunctioning

I am facing issues with updating multiple partial views using jQuery, MVC, and JSON. The partial views on my page are not getting updated. Below is the code for my view: Here is the code for my controller: public class GetStudentsController : Controlle ...

Accessing local JSON data through JavaScript

I am looking to access a JSON file locally using JavaScript. The file is named "posts.json" and contains the following information: { "post0": "<empty>", //1 "post1": "<empty>", //2 "post ...

Storing the closed state of a pop-up box in localStorage for future reference

I'm struggling to get localStorage working properly on my website (). Here's what I need to achieve: A newsletter subscription pop-up on every page - this part is functioning correctly An option for users to click 'X' to close the po ...

In Vue, the concept of using the debounce method is not clearly defined

I am aware that using the arrow syntax for a method can cause 'this' to not be mapped to the Vue instance. In my case, I am utilizing lodash.debounce and I don't think I'm using the arrow syntax here? Encountering Error: Cannot read pr ...

The state may be modified, but the component remains unchanged

I've been tasked with implementing a feature on a specific website. The website has a function for asynchronously retrieving data (tickets), and I need to add a sorting option. The sorting process occurs on the server side, and when a user clicks a s ...

Ways to validate the existence of URLs from different domains with javascript

I'm attempting to verify the existence of a URL from another domain on my own domain ('https://radiusofficefurniture.ie') using JavaScript like this: var request = new XMLHttpRequest(); request.open('GET', 'https://www.mozil ...

The radio buttons that can be deselected are not accurately retaining their previous value

I'm currently working on a directive that will allow me to deselect an existing radio input. However, I've run into an issue where the directive is not accurately tracking the previously selected value. The objective is to have the radio set to e ...

update the componentWillMount() function

I am currently exploring the code found at https://github.com/Spyna/react-store/blob/master/src/createStore.js What adjustments do I need to make in order to align with the deprecated componentWillMount lifecycle method? CreateStore const createStore = ...

"Implementation of a dropdown menu featuring deletion capabilities within an ng-repeat loop

Is there a way to instantly reflect the view after deleting a tag on click? Currently, the change is only visible after refreshing. <div class="dropdown"> <span ng-repeat="tag in tag track by $index" data-toggle="dropdown">[[t ...

Storing input values in the state using Typescript by default

Upon launching, my activeField state is initially empty. However, when a user focuses on the field, it gets added to the state. I am encountering a warning in Typescript because when I attempt to update the selectionEnd of that field, it tells me: Property ...

What is the best approach to passing multiple variables to a JavaScript function in HTML/PHP?

Seeking help with calling a javascript function from PHP through embedded HTML code. Below is the script: <script> // THE FOLLOWING JAVASCRIPT FUNCTION REDIRECTS TO EDITUSER.PHP AND PASSES USERID VALUE. function startMaint(mo, yr){ ...

When attempting to retry in Next.js, the props obtained from getServerSideProps may

Currently, I am facing an issue with sending axios requests in getServerSideProps and passing the value through props via SSR to the client. The challenge lies in including a token in the header using an instance. In case the token expires, I utilize refre ...

Caching HTML5 videos in Google Chrome

I am currently in the process of building a website and have successfully added an HTML5 video. However, I encountered an issue when attempting to change the video file in the background for users to upload a new one. Despite updating the video URL, Chro ...

AngularJS URL Transformation: A How-To Guide

While building a single page web app, it's important to keep the URL from changing. I have achieved this using jQuery by loading HTML content from the backend server when a user clicks on a link. However, I'm curious about how AngularJS handles ...

I am facing issues with the functionality of $setValidity for my validation process

Within my form named gamesConfig, I need to display an error message under certain conditions. <form method="post" name="gamesConfig" novalidate> <p ng-show="gamesConfig.selectedGames.$invalid.gamesduplicate">It seems this game already exi ...

Having trouble with a JQuery selector not functioning properly when trying to select a class in the HTML that contains a

Looking for help with a JQuery selector to target the title of a YouTube video. Here's the HTML snippet: <div class="ytp-title-text"> <a class="ytp-title-link yt-uix-sessionlink" tabindex="13" target="_blank" ...

Assign a value to the input field based on changes made in another input field

I am brand new to the world of JavaScript and currently grappling with setting a value in an input field based on the onchange event of another input field. Here is my code sample for input field 1: <input type='text' onchange='methodTh ...