Using the ng-repeat directive to create dynamic data-titles in AngularJS

I need help with displaying dynamic headers in an Angular table for certain <td> elements. Here is a sample of my data:

let data = [    
    {
        id: 1,
        name: 'name',
        fields: {
            field1: { value: '123'},
            field2: {value: 'macx'}
        }
    },
    {
        id: 2,
        name: 'name2',
        fields: {
            field1: { value: '456'},
            field2: {value: '3333'}
        }
    }
]

I want these fields to be displayed as additional columns in the same table dynamically. Since the fields are dynamic and unknown, I am looking for suggestions on how to achieve this through code.

<tr ng-repeat="data in $data">
    <td data-title="'id'|translate"
        sortable="'id'">
    {{data.id}}
    </td>
    <td ng-repeat="(key, value) in data.fields track by $index"
        ng-show="columnsHash[key]"
        data-title="customFieldsTitles[$index]"
        filterable="{field:'fields', type:'text', align:'LEFT'}"
        data-title-text="customFieldsTitles[$index]">
      {{value && value.value || ''}}
    </td>
    <td ng-show="columnsHash.totalBenefitTarget"
        data-title="'target_total_benefit' | translate"
        sortable="'total_benefit_target'"
        style="text-align:center;"
        filterable="{field: 'total_benefit_target', type:'number_range', options: {min:  Number.MIN_VALUE, max: Number.MAX_VALUE}}">
      {{data.total_benefit_target | number: 0}}
    </td>
    <td ng-show="columnsHash.totalBenefitActual"
        data-title="'actual_total_benefit' | translate"
        sortable="'total_benefit_actual'"
        style="text-align:center;"
        filterable="{field: 'total_benefit_actual', type:'number_range',
        options: {min:  Number.MIN_VALUE, max: Number.MAX_VALUE}}">
      {{data.total_benefit_actual | number: 0}}
    </td>
<tr>

The order of the columns is crucial, so the structure should follow the example above. Any insights or alternative approaches to achieve the desired view are greatly appreciated. Thank you!

Answer №1

When working with an angular table, I encountered a problem where I needed to use scope.$column to render table columns. To solve this issue, I implemented scope binding in my code.

Here is a snippet of the code that demonstrates how I used scope binding to render table columns:

<table ng-table="tableParams" ng-init="initTable()">
<td ng-repeat="(key, value) in data.fields"
                data-title="'Custom Field'"
                sortable="'fields'"
                filterable="{field:'fields', type:'text', align:'LEFT'}">
              {{value && value.value || ''}}
 </td>
</table>

In the controller section of the code, I initialized the table columns using the initTable function. After loading the data for the table, I then called the updateCustomFields function to update the columns' titles dynamically.

The updateCustomFields function goes through each column and checks if the title is 'Custom Field'. If it finds a match, it creates a new column with a different label based on the customFieldsHash object. This newly created column is then inserted into the tableColumns array at the appropriate position.

By implementing these functions, I was able to successfully render table columns with dynamic titles based on the values from the customFieldsHash object.

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

Preventing users from copying and pasting information from my form by implementing javascript restrictions

I'm looking for a solution to prevent users from copying and pasting in my form using JavaScript. I want to restrict the ability to paste or copy any content into the form. Any assistance would be greatly appreciated! ...

Trouble with jQuery not loading properly in HTML

I'm experiencing an issue with a code I want to use, but it isn't responding. Even though I've verified that the code is correct because it's on jsfiddle: http://jsfiddle.net/User86745458/ztz4Lf23/ However, when I try to copy and paste ...

Warning message regarding unhandled promise rejection in NestJS websockets

I've encountered a puzzling issue while attempting to integrate an 'events' module into my application to utilize websockets. Upon adding the module, an unexpected error surfaced: (node:59905) UnhandledPromiseRejectionWarning: Unhandled pro ...

The mobile-responsive dropdown navigation bar functions well on browsers with small widths, but does not work properly on my phone

I am experiencing an issue with the mobile responsive dropdown navigation bar on my website. It works perfectly fine on a small width browser, but when I try to open it on my phone, nothing happens. This is puzzling me as I am new to making websites respon ...

Retrieve the service variable in the routing file

How do I access the service variable in my routing file? I created a UserService with a variable named user and I need to use that variable in my routing file. Here is the approach I tried, but it didn't work: In the routing file, I attempted: cons ...

Creating a flowchart of a finite state machine within a browser-based software platform

If you're curious about the core logic behind my application, check out this link for a great explanation: Code Golf: Finite-state machine! I plan to implement this logic to create finite state machines on my web app using a library. I've been ...

What are the recommended callbacks for initiating ajax calls and managing files/chunks during dropzone chunk uploading?

I am currently working on implementing chunk uploading using dropzone js and php. My main concern is regarding the placement of ajax calls in this process. When dealing with single file uploads, specifying the URL parameter is sufficient. However, when ...

The uib-datepicker-popup is failing to reopen

I'm encountering an issue with the uib-datepicker-popup where once I select a date from the calendar, I am unable to reopen it without refreshing the screen. I've checked the ng-click function and it correctly sets the is-open flag to true, but t ...

utilize makeStyles to modify button text color

Initially, my button was styled like this: style={{ background: '#6c74cc', borderRadius: 3, border: 0, color: 'white', height: 48, padding: '0 30px', }}> It worke ...

Using AJAX to transfer a variable from a range slider to a PHP query

I'm currently trying to pass a JavaScript variable from a range slider to a PHP query. The goal is to have the front-page of my Wordpress theme display all posts tagged with the value selected on the range slider without having to refresh the page. To ...

Ensure to utilize object identities while employing QUnit.deepEqual() with an array

Let's set the scene: I have a function that returns an array of objects. These objects do not have any enumerable properties, but are sourced from a common cache or store. In my test cases, I want to verify if the contents of the returned array are a ...

Ways to evaluate a value in JavaScript

After performing an ajax operation to retrieve data, I am using javascript to perform conditional checks. Here is the output when printing the response: document.write(response) Result: [object Object] When printing something like document.write(JSON.s ...

React css modules to enhance styling in your web project

I am in the process of incorporating a CSS module into the login component. Currently, I have a style.css stylesheet located in the src/styles folder, which is responsible for loading global styles. However, I now want to customize the login component by a ...

Error encountered with Vuetify stepper simple component wrapper and v-on="$listeners" attribute

I'm working on developing a custom wrapper for the Vuetify Stepper component with the intention of applying some personalized CSS styles to it. My aim is to transmit all the $attrs, $listeners, and $slots. I do not wish to alter any functionality or ...

I am eager to run the code that I retrieved from the server. I have access to the code in my console and I desire for it to execute on the main browser page

Currently, I have a simple Google Chrome Extension that includes a button. By using AJAX, I am fetching a script from a server in my browser's console. Essentially, clicking on the extension reveals a button which, when clicked, fetches the script fro ...

Saving user input as a local variable to be utilized on a different web page

I am attempting to capture a user input from a form and then utilize that variable on a separate page. This process should be straightforward, but I am not receiving any results and I am unsure of the reason why. Here is the code on the first page: <di ...

The function within filereader.onload is not running properly in JavaScript

When working with FileReader to read a file and convert it to base64 for further actions, I encountered an issue. Although I was able to successfully read the file and obtain its base64 representation, I faced difficulties in utilizing this data to trigger ...

Store user input in a paragraph

I want to create a unique program that allows users to input text in a field, and when they click "Start", the text will appear in a paragraph backwards. I plan to use Html, jQuery, and CSS for this project. Can anyone provide guidance on how to achieve th ...

Why is my Angular 2 service not showing up in my application?

Trying to access a JSON file using an Angular service has been unsuccessful. While I can easily read and bind the JSON data without the service, attempting to do so with the service results in an error message: Failed to load resource: the server responde ...

Adding a combination of HTML and Javascript to an element can result in unexpected behavior

http://jsfiddle.net/PeKdr/ Encountering an issue when having a JavaScript variable that contains both HTML and JavaScript, resulting in unexpected behavior in the output window. Neither of the buttons - one triggering the function appendTheString() or the ...