Iterate through a generic array to populate a table using ng-repeat

In the scenario I'm currently facing, I am working on creating a common reusable table structure using a directive. The goal is to display different JSON data in both the table header and body.

Below is the controller code:

angular.module('plunker', []);

function MainCtrl($scope) {
  $scope.firstJson=[{name:"abc1",empid:10215},{name:"abc2",empid:10216},{name:"abc3",empid:10217},{name:"abc4",empid:10218},{name:"abc5",empid:10219}];
  $scope.secondJson= [{product: "mobile", price: "10000"}, {product: "camera", price: "12000"}];
  $scope.name =  $scope.firstJson;
  $scope.tableHeading=["heading1","heading2","heading3"];
  $scope.toggle=true;
}

The directive code is as follows:

angular.module('plunker').directive('sampleDirective', function(){

  return {
    restrict: 'A',
    scope: {
      name: '=',
      tableHeading:'='
    },
    templateUrl: 'reverse_template.html',
    replace: true,
  };
});

To see a demo of this directive in action, you can visit the following Plunker link: Demo

Here are the final outputs for the firstJson and secondJson respectively: https://i.stack.imgur.com/XOnni.png, https://i.stack.imgur.com/AtgXU.png

Any assistance on this matter would be greatly appreciated.

Answer №1

The initial two arrays are the ones you provided, each with 2 columns.

To demonstrate its flexibility, I included a third array with 3 columns to show that it works seamlessly.

Regardless of the number of columns or rows, this solution will function effectively.

Tip: Remember to update the templateURL to the correct file and transfer the content within script ng-template to an external file.

… (the rest of the code remains unchanged)

Answer №2

If you're facing a problem, one solution is to separate column entries based on the keys of your array of objects and then display rows dynamically according to the columns. Here's an example of how you can achieve this:

Use the following code snippet for your directive:

return {
  restrict: 'A',
  scope: {
    columns: '=',
    rows   : '='
  },

  replace: true,

  link: function ($scope) {

    $scope.displayData = function (row, column) {
      return row[column];
    };
  }
};

Your HTML markup should resemble the following structure:

<tr>
  <th ng-repeat="column in columns">{{column}}</th>
</tr>
<tbody>
  <tr ng-repeat="row in rows">
    <td ng-repeat="column in columns>{{displayData(row, column)}}</td>
  </tr>
</tbody>

In your JavaScript file, consider defining it as follows:

function MainCtrl($scope) {
  $scope.rows = [
    {
      'column_1': 1,
      'column_2': 2,
      'column_3': 3
    },
    {
      'column_1': 1,
      'column_2': 2,
      'column_3': 3
    }
  ];

  $scope.columns = ['column_1', 'column_2', 'column_3']
}

A helpful tip - if you need to extract keys dynamically from an array of objects, simply take one item, retrieve its attributes, and assign them to $scope.columns.

For instance:

var extractAttributes = function (object) {
  var attrs = [];

  angular.forEach(object, function (value, key) {
    attrs.push(key);
  });

  return attrs;
}

Another useful tip - you can implement column separation within the directive by utilizing $watch to monitor changes in row data and extracting columns accordingly.

I hope this information proves helpful!

Answer №3

My chosen method was as follows:

<div>
  Hello, {{name}} ,{{tableHeading}}

 <table ><tr><th ng-repeat="(key,value) in name[0]">{{key}}</th></tr><tbody><tr ng-repeat="names in name"><td ng-repeat="(key, value) in names">{{value}}</td></tr></tbody></table>

</div>

click here for more information

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 role does conditional logic play in the compile or link function of an AngularJS directive?

In my $scope, there is a JSON object named data. Within this object, there exists a member called items that can be either an Object or an Array of Objects. Due to this variability, the use of ng-repeat is not feasible: <ul> <li ng-repeat="it ...

Tips for preventing text wrapping in off-canvas design

Seeking advice for my Web Application prototype - looking to prevent text wrapping in off-canvas menu paragraphs using CSS or JS. New to building this type of menu, I used an example from W3Schools to achieve the current design. <!DOCTYPE html> ...

Executing a simulated onClick event in jQuery

Attempting to create a simulated onclick event on a drop-down menu has proved challenging for me. An IE object is being used to navigate to a page, where I need to modify a dropdown menu that contains an onchange event: $('select[name="blah"]') ...

Utilizing References in React Components

One of the challenges I am facing involves a Container that needs references to some of its child components: const Container = () => { const blocks: HTMLDivElement[] = []; return ( <div> <Navigation currentBlock={currentBlock} ...

The document.getElementsByClassName method in JavaScript is returning an Array with a length property value of 0

My HTML contains a list of li elements with one class. I am attempting to collect them all and place them in an array to determine how many have been gathered. However, when I attempt to display the number using the .length property of the array returned b ...

The Angular Universal error arises due to a ReferenceError which indicates that the MouseEvent is not

I am encountering an error while trying to utilize Angular Universal for server-side rendering with the command npm run build:ssr && npm run serve:ssr. This is being done in Angular8. /home/xyz/projects/my-app/dist/server/main.js:139925 Object(tslib__WEB ...

What are the steps to effectively utilize <ul> for showcasing scrolling content?

I stumbled upon and found it to be a great inspiration for my project. I tried replicating the layout of the listed items on the site: .wrap { display: block; list-style: none; position: relative; padding: 0; margin: 0; border: ...

Unable to utilize Socket.io version 2.0.3

When it comes to developing a video chat app, I decided to utilize socket.io. In order to familiarize myself with this library, I followed various tutorials, but unfortunately, I always encountered the same issue. Every time I attempted to invoke the libr ...

Requiring addresses for Google Maps in order to display directions

To display the directions between two addresses based on the chosen transportation mode, I need to pass the addresses to the code in page 2. After the user selects two cities from a Dropdown box on page 1, they will be sent to the code to show their locati ...

Why does starting up the Firebase emulators trigger the execution of one of my functions as well?

Upon running firebase emulators:start --only functions,firestore, the output I receive is as follows: $ firebase emulators:start --only functions,firestore i emulators: Starting emulators: functions, firestore ⚠ functions: The following emulators are ...

Utilizing a dedicated settings configuration in a JSON file

I'm interested in finding out how to implement a separate file in Angularjs for storing settings data. For example, I have a service that contains a list of languages like this: .service('Language', function () { this.getLanguageSettings ...

Steps to generating a dynamic fabric canvas upon opening a new window

There seems to be an issue with the code below. When I click the button next to the canvas, my intention is to have a new window open displaying the canvas in full view. However, it's not working as expected. Can someone please assist me in troublesho ...

"Encountered an issue with combining multiple meshes that share the same geometry but have

I wrote a loop that generates multiple Mesh objects with various geometries, where each mesh corresponds to a specific texture: var geoCube = new THREE.CubeGeometry(voxelSize, voxelSize, voxelSize); var geometry = new THREE.Geometry(); for( var i = 0; i ...

Consistently receiving the identical result even when the checkbox remains unselected

Displaying a Checkbox Input <input id="idCheckbox" name="check" type="checkbox" value="AllValue" style="width: auto; height: auto; font-weight: bolder;" data-bind="checked: idCheckbox" /> The checkbox input will always have the value "AllValue ...

Can we access local storage within the middleware of an SSR Nuxt application?

My Nuxt app includes this middleware function: middleware(context) { const token = context.route.query.token; if (!token) { const result = await context.$api.campaignNewShare.createNewShare(); context.redirect({'name': &a ...

Executing multiple HTTPS requests within an Express route in a Node.js application

1 I need help with a route that looks like this: router.get('/test', async(req, res)=>{ }); In the past, I have been using the request module to make http calls. However, now I am trying to make multiple http calls and merge the responses ...

Angular displaying a slice of the data array

After following the example mentioned here, and successfully receiving API data, I am facing an issue where only one field from the data array is displayed in the TypeScript component's HTML element. Below is the content of todo.component.ts file im ...

Refreshing a specific div within an HTML page

I am facing an issue with the navigation on my website. Currently, I have a div on the left side of the page containing a nav bar. However, when a user clicks a link in the nav bar, only the content on the right side of the page changes. Is there a way t ...

"Exploring the Power of TypeScript Types with the .bind Method

Delving into the world of generics, I've crafted a generic event class that looks something like this: export interface Listener < T > { (event: T): any; } export class EventTyped < T > { //Array of listeners private listeners: Lis ...

Achieving 10 touchdowns within a set of 5 plays during a football game

Receiving a page from an external site where I have no control. The table structure is as follows: <table><tbody> <!-- headers --> <tr><td></td> <td></td> <td></td> <td>< ...