How can we customize the column headers in UI Grid using AngularJS?

I have a data-driven application that updates table headers dynamically based on user clicks. The data is loaded from a JSON File.

When using a normal table with ng-repeat="heading in gridHeaders">{{ heading }}, everything works fine. However, when I switch to ui-grid and the view is updated with new data, the grid cells become empty while the column headers remain static. How can I update the column definition in ui-grid?

Here is the link to the JSFiddle http://jsfiddle.net/masoom/svcxh6hu/7/

controllers.js

$scope.gridOptions = {
    data: 'grid',
   columnDefs : '' /* not sure how to use the <ng-repeat="heading in gridHeaders"> {{ heading}} here*/
};

/* 
 Watch for the change in the Tree's current node. 
 When user clicks on a node, $scope.currentNode will update
 */
$scope.$watch(function () {
    return $scope.currentNode;
}, function () {
    $scope.displayGrid(angular.fromJson($scope.currentNode.json));
});

/*
Sets the Grid's data model. The view will update when this is called.
*/
$scope.displayGrid = function (data) {
    $scope.grid = data;
    $scope.gridHeaders = new Array();
    if (typeof data != 'undefined') {
        for (var key in data[0]) {
            $scope.gridHeaders.push(key);
        }
    }
}

index.html

<table ui-grid="{ data: grid }" class="grid1" ng-show="gridHeaders.length>0" >

                <thead>
                    <tr>
                       <th ng-repeat="heading in gridHeaders">{{ heading }}</th>
                </tr>
            </thead>
            <tbody>
                <tr ng-repeat="obj in grid">
                    <td ng-repeat="heading in gridHeaders">{{ obj[heading]      }}</td>
                    </tr>
                </tbody>
        </table>
 <div ui-grid="gridOptions" class="grid1" ng-show="gridHeaders.length>0" >    
          </div>

Answer №1

$scope.headers =  [{name: 'Name', age: 'Age'}, {name:'Occupation', displayName:'Age'}];            
 $scope.sections =  [{field: 'name', title: 'Name'}, {field:'age', title:'Age'}, {field:'occupation',title:'Occupation'}];  
$scope.dataOptions = { 
    values: 'dataSet',
    definitions: 'headers'
};

Answer №2

This particular query demonstrates that making changes to the gridOptions.columnDefs will result in updates to the columns within the grid. However, if you assign a new object or array to columnDefs, it will not have any effect because the reference to the object in the api will be lost. Learn how to dynamically update angular ui-grid columnDef

Although I haven't come across any refresh method that would be helpful, utilizing this approach eliminates the need for calling refresh().

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 is the origin of the libraries found in npm-shrinkwrap that do not match the packages listed in package.json?

I'm puzzled by the presence of `express` in my `npm-shrinkwrap` file as a main dependency. Despite this, `express` is not listed as a dependency in my `package.json` file. I can't find any usage of it in my project. It's not included a ...

What is the best way to include a schema within another schema using Mongo, NodeJS, and Angular?

In the process of creating a MEANjs app, I have set up two schemas: one for users and one for claims. My goal is to be able to access user information from within a claim. Currently, I am able to retrieve the display name in my view using {{vm.claim.user. ...

Having issues with the `onlyCountries` property in the React phone input 2 component when using

I've integrated the react-phone-input-2 library to include phone number fields in my project. I need to provide selected countries only for the country codes. I'm fetching iso2countrycodes from the server and passing them to my Phone input compon ...

Utilizing AngularJS to dynamically display content based on specific grandson JSON property

My application currently contains the following JSON data: { "Success":true, "Error":null, "Data":{ "VersionId":1, "SecretaryId":1, "SecretaryName":"Foo", "Status":1, "Schools":[ { "Schoo ...

Navigating tables with jQuery using a loop and extracting data from two tables with matching row names

I am facing a challenge with a function that combines data from two tables, each containing a column named "name". How can I specify which table's name should be displayed? function createTableRow(customers) { var data = JSON.parse(customers.resu ...

Navigating with Express 4

Currently, I am in the process of implementing Passport for user signup by referring to this helpful guide: https://scotch.io/tutorials/easy-node-authentication-setup-and-local Overall, everything is functioning properly except for one issue - after a su ...

Need help making switch buttons in react-native?

Using the library found at this link has been quite successful on my iPhone, but it does not display properly on Android. It appears as shown here. ...

"Learn the art of refreshing data in AngularJS following the use of $emit event handling

I am in need of assistance with AngularJS. How can I re-initialize a variable in scope after using emit? Here is an example code snippet: $scope.uiConfig = {title: "example"}; $scope.$emit('myCustomCalendar', 'Data to send'); $scop ...

angular material theme malfunctioning

Within the configuration block, I have set up the following: .config(['$urlRouterProvider', '$stateProvider', '$locationProvider', '$mdThemingProvider', function ($urlRouterProvider, $stateProvider, $locationProvid ...

What are the uses of AngularJS conditional statements?

Currently, I am following an AngularJS tutorial and encountering an issue. In the controller, I have an array with various points being displayed using ng-repeat {{feature.name}} {{feature.description}} My confusion lies in the fact that there is a third ...

Is there a way to automate the distribution of tasks to users in order to ensure that each user receives an equal number of assignments?

I'm in the process of developing an automated task manager that assigns tasks to users based on their role. Currently, I'm randomly selecting a user with the same role as the task from the list of users and assigning the task to them using math.r ...

I am curious as to why jQuery offers the done() method for promises, while the JavaScript promises documented by Mozilla do not. Is there a way to incorporate a done() method in vanilla JavaScript promises if needed?

What sets apart the Promises in Mozilla's JavaScript documentation (view API page) from those in jQuery's Promises (see API page)? It appears that Mozilla's promise only includes 2 methods: then and catch. On the other hand, jQuery's p ...

Ways to verify the click status of a button prior to initiating an AJAX request with jQuery?

I am facing an issue with a button that needs to be clicked by the user before submitting the form. Here's the code snippet for the button: $('#chooseButton') .on( 'click', function() { console.log("user ha ...

Prevent users from changing dropdown options after a form submission fails using Javascript and Jquery

Currently, I am pursuing the tech degree at Team Treehouse and my third project involves creating an interactive form. To simplify my issue, I will outline it in bullet points: The credit card payment method should be preselected when the page loads. I n ...

Steps to resolve the "cannot get product" error on Heroku after submitting a value

view the image description hereI have been working on a MERN full stack project and everything was functioning correctly in my local environment. However, upon deploying it to Heroku, I encountered an error which is displayed below. All other APIs are fu ...

You do not have the authorization to access this content

I have been working on a Laravel web application to upload images into a data table and allow users to download the uploaded image on click. Initially, everything was working fine until I made changes in the code from return '{!! Html::link('ima ...

embedding JSON data into the main template

I'm looking to include a JSON string by injecting some JavaScript on each page. In the master page, I have: public partial class TheMasterPage : System.Web.UI.MasterPage { protected void Page_Init(object sender, EventArgs e) { if (Session[ ...

The processing indicator fails to function properly when trying to refresh a jQuery datatable

I am currently customizing the loading indicator for the datatable using a spinner called startLoadGlobal(SPINNER_DATA_TABLE_FINANCEIRO_CARREGAR_REGISTROS) in jQuery. It works correctly when I initially load the datatable, however, when I reload it, the sp ...

There was an issue while trying to import troika-three-text using the importmap

My goal is to incorporate the troika-three-text into my Three.js script by importing it through HTML, as demonstrated below: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name=&q ...

How can buttons be replicated in an angular-friendly manner?

I need to implement a follow button functionality for a specific user that should toggle its text between "Follow" and "Followed" when clicked. The follow button may appear in various modules across the page, and when clicked, it should update in all insta ...