Changing the key name for each element in an array using ng-repeat: a guide

In my current project, I have an array of objects that I am displaying in a table using the ng-repeat directive.

<table>
    <thead>
        <tr>
            <th ng-repeat="col in columnHeaders">{{col}}</th> //['Name', 'Bank Name','Code', 'Type','Status'];
        </tr>
    </thead>
    <tbody>
        <tr ng-repeat="row in data track by $index">
          <td ng-repeat="col in columnRows">{{row[col]}}</td> //['name', 'bankName','code', 'type','isActive'];
        </tr>
    </tbody>
</table>

Although I am using ng-repeat on both the <th></th> and <td></td> elements, I encountered an issue where the names of my columnHeaders and row properties (columnRows) are different. I wanted to align the property name with the column header name while using ng-repeat on the <td></td> tag. I considered using an alias with 'as' but was unsure how to implement it for each element. Can anyone provide guidance or assistance?

Answer №1

Optimize your code by using a single array of keyHash instead of two columnRows and header rows (array of string).

View the updated fiddle here

The revised code should look like this:

<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>

<body ng-app="myApp" ng-controller="myCtrl">

<table>
    <thead>
        <tr>
            <th ng-repeat="col in keyHash">{{col.displayStr}}</th>  
        </tr>
    </thead>
    <tbody>
        <tr ng-repeat="row in data track by $index">
          <td ng-repeat="col in keyHash">{{row[col.key]}}</td> 
        </tr>
    </tbody>
</table>

<script>
var app = angular.module("myApp", []);
app.controller("myCtrl", function($scope) {


$scope.keyHash = [
 {key:'name',displayStr:'Name'},
  {key:'bankName',displayStr:'Bank Name'},
   {key:'code',displayStr:'Code'},
    {key:'type',displayStr:'Type'},
     {key:'isActive',displayStr:'Status'}
]

  $scope.data = [
   {
   name:'James',
   bankName:'RBL',
   code:'1234',
   type:'Saving',
   isActive:true
   },
   {
   name:'Riyan',
   bankName:'DSB',
   code:'1234',
   type:'Current',
   isActive:true
   }
  ];

});
</script>

</body>
</html>

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

Is it possible to access the DOM element within which the registerHelper is being used?

My current challenge involves using Template.registerHelper to create a helper that can output either class1 or class2 based on a boolean value. Additionally, I want the output to include an initial class only if it's the first time the helper is call ...

Issues with the functionality of Google Translate's JavaScript code snippet are causing

After trying out the code snippet provided on w3schools.com, I encountered a discrepancy between the results displayed on the website and those on my personal computer. <div id="google_translate_element"></div> <script> function googleT ...

Testing a subordinate function within the main method that involves HTTP request authorization

Dealing with a tricky situation here, hoping for some guidance. So I'm working with a main method that serves as an api endpoint. This method calls another function to check if the user is authorized to access this endpoint or not. The sub-method, r ...

How come I am unable to return an array from an angular factory function if arrays are considered objects?

Why is it that we can return an object, but not an array if an array is also an object? ...

Crack open a JSON object

I am struggling to parse a JSON object. It seems like the code is not working, can you help me? var mock_data = { "available": [{ "UserID": 7, "UserName": "Manoj", "Language": "Java", "Score": 9, "TimeLimit": 4.0 }, { "UserID ...

Where to begin with Angular materials?

Here is a snippet of my Angular materials test code: <div class="radioButtondemoBasicUsage" ng-app="MyApp"> <form ng-submit="submit()" ng-controller="AppCtrl"> <p>Selected Value: <span class="radioValue">{{ data.group1 }}< ...

Unexpected outcomes when trying to sort and paginate React-Table

Experiencing unexpected results with react-table integration for pagination and sorting. Merged examples from the react-table repository. Encountering an issue where table hooks reset the page index on re-render, causing fetchData to be called twice during ...

extracting the value of a chosen radio button in AngularJS using HTML

When attempting to retrieve the selected value from a radio button, I am encountering an issue where choosing "teacher" still shows as "student." Here is the HTML file: <!DOCTYPE html> <html ng-app="phase2"> ... (HTML code continues) Rige ...

Deselect a checkbox by selecting a radio button with just Javascript code

Hey there! I'm currently delving into the world of pure JavaScript and could really use some guidance on a particular issue. Here's what I'm aiming to accomplish: I'd like to design a checkbox that triggers the opening of a window whe ...

Ensure that the central section of the slider remains illuminated

Looking for help with customizing my "product" slider, lightSlider. I want the middle div to always be highlighted when navigating through the slider. Here's what it looks like currently: Link to screenshot - current. My goal is to achieve this look: ...

Error: Request Timed Out - The asynchronous callback function was not executed within the specified timeout set by the jasmine.DEFAULT_TIMEOUT

Currently, I am in the process of testing my Ionic app using Jasmine. Below is a snippet from my test suite: beforeEach(() => { auth = new Authentication(<any>new HttpMock(), <any>new StorageMock()) user = new MockUser(); head ...

Issue with generating WebGL shaders

As I embark on creating a basic application in WebGl and JavaScript following online tutorials, I encountered a peculiar issue while working on some fundamental shaders. The function responsible for generating the shader program presents itself as follows: ...

Access file using operating system's pre-installed application

How can I open a file using the default application for that file type on different operating systems? For example, when opening an image.png on Mac, it should open with Preview, and on Windows with Windows Photo Viewer. I know you can use open image.png ...

Having trouble with Vuejs uploading multiple images when not using a CDN?

Hello! I am currently experimenting with implementing this specific plugin for uploading multiple images using vue.js. Below you can find the code snippet that I have been working on. <!DOCTYPE html> <html lang="en> <head> &l ...

Controller unable to access form inside ng-repeat loop in AngularJS

Looking to access a form object within my controller. The form is located inside an ng-repeat block with a dynamic name, and I should be able to access it since version 1.3. JavaScript: var app = angular.module('app', []); app.controller(' ...

Struggling to prevent keyboard-triggered date changes in the MUI DatePicker API

Link to CodePen: codepen.io/s/jk3sgj?file=/demo.tsx Is there a way to prevent users from manually typing in dates and force them to select a date from a modal picker instead? I tried using the ReadOnly prop, but it disabled the entire input field, includ ...

Managing toggles for save and edit buttons in Vue - a comprehensive guide

I am currently working on a Vue 'app' within a larger Django application as a means to enhance my understanding of Vue. My objective is to create unique forms that can be edited independently. I have been experimenting with this for some time n ...

Getting the value of a JSON object in CodeIgniter can be easily achieved by using the appropriate

My current project involves using the codeigniter framework to build a website. I am making an AJAX request with jQuery to retrieve data from the server. I have experimented with two different methods of receiving the data: one in a PHP associative array a ...

A guide to efficiently pre-rendering secure APIs on a server for Next.js

Currently, I am working on a project that involves fetching data from multiple pages. However, the challenge lies in the fact that all APIs are secured, except for the initial API that fetches data for the home page. Furthermore, all other APIs are protect ...

Cannot locate module: Error: Unable to find the path '../containers/Layout' in '/home/yusquen/Projectss/react-shop/src/components'

https://i.stack.imgur.com/U1097.png description of image goes here Issue with module: Error: The file '../containers/Login' could not be found in the 'react-shop/src/components' directory. ...