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

AJAX request post parameters not recognized in ColdFusion form scope

I am currently developing a ColdFusion 8 training application that involves creating AJAX requests without using any libraries like jQuery. This is to support a basic CRUD application where data is retrieved and processed through various layers of the syst ...

Is there a way to adjust a 5-minute countdown interval timer by 1 minute in a react JS application?

I am in need of creating a 5-minute interval timer using react JS, with a 1-minute offset. The current timer I have functions like this: 1:00 => 1:05 => 1:10 => 1:15 => 1:20. However, I require it to be adjusted to display: 1:01 => 1:0 ...

What steps are involved in generating a scene dynamically with A-Frame?

Looking to transition from declarative coding in js and html to a programmatic approach with Aframe? You might be wondering if it's possible to modify your scene dynamically, here is an example of what you're trying to achieve: <!DOCTYPE html ...

Switch the dropdown selection depending on the checkbox status

I'm currently facing a bit of confusion with my project. I am constrained by an existing framework and need to come up with a workaround. To simplify, I am tasked with populating a dropdown list based on the selected checkboxes. I have managed to get ...

Nightwatch is a tool that allows you to interact with elements on a webpage by clicking on an element within

I have a scenario on my website where I have two separate div elements: <div class="wg-block" data-reactid="10" <div class="wg-header" data-reactid="11"/div> .... <h4 class='condition'> "Text" </h4> <div cl ...

When using express, it is important to note that parameters cannot be accessed directly through the request.body

How can I successfully submit a form from my angular app? var formdata={ date:$scope.myForm.date ,name:$scope.myForm.name ,mobile:$scope.myForm.phone }; $http({ method:"POST" ,url:'/forms/submit' ...

Repeated calls to Angular's <img [src]="getImg()"> frequently occur

Can someone help me figure out what's going on here? Recently, I set up a new Angular project and in app.component.html, I have the following code: <img [src]="getDemoImg()"> In app.component.ts: getDemoImg(){ console.log('why so m ...

Display labels for each tick on the Kendo slider in AngularJS

When using the Kendo UI Core Slider, I noticed that the default label for ticks only appears every 5. In my sliders, the max value is dynamic and can sometimes be as low as 3 or 4. This results in the user only seeing a 0 (as the min) and a few ticks on t ...

Discovering the Nearest Textfield Value Upon Checkbox Selection Using JQuery

How can I retrieve the value of the nearest Textfield after selecting a checkbox? This HTML snippet serves as a simple example. In my actual project, I have dynamically generated lists with multiple checkboxes. I require a way to associate each checkbox wi ...

Angular 5 - Creating a dynamic function that generates a different dynamic function

One of my latest projects involved creating a versatile function that generates switch-case statements dynamically. export function generateReducer(initialState, reducerName: ReducerName, adapter: EntityAdapter<any>): (state, initialState) => ISt ...

Determining the Testing Status of a Node Package Management (NPM) Package

As someone who is new to Node.js and NPM, I have a question that may seem naive. Is there a method to determine if a package published on NPM has been tested? And if so, can this process be automated? Are there any tools or frameworks available that can va ...

Successive promises of catches

Here is a situation that I am dealing with: controller.ts methodA(): void { myServive.someMethod() .then( () => console.log("then") ) .catch( e => { console.log("catch"); }); } service.ts someMethod(): ng: ...

Validation customized through offspring control

Currently, I am dealing with a situation where I need to transclude all controls within a directive that has its own form element and buttons. The model in this context includes a property for the total capacity and another property that consists of compar ...

Are there any alternatives to jQuery address in the realm of dojo?

Currently, I am working on developing an ajax application using dojo. I am curious if there is a feature comparable to jQuery Address in terms of functionality. My goal is to implement ajax-based hash url navigation similar to Twitter and Facebook using do ...

Upon the second click, the addEventListener function is triggered

When using the window.addEventListener, I am encountering an issue where it only triggers on the second click. This is happening after I initially click on the li element to view the task information, and then click on the delete button which fires the eve ...

Is it possible that $watch does not function properly for instantaneous statements?

Are you tired of hearing the same old story? Well, I'm here to bring something new to the table. You see, I'm a novice in the world of bla bla... Recently, I've encountered a perplexing situation with my code. In the snippet below, whenever ...

Transferring session data through AJAX in PHP

I'm currently developing an app using PhoneGap. However, PhoneGap only supports HTML, CSS, and JS, not PHP. This led me to the workaround of placing the PHP file on a remote server and using AJAX to call it via the server's URL. My issue now is ...

Node.js: Extracting parameters from the URL

When working with Rails, I make a POST request to my server: response = Typhoeus::Request.post("http://url.localtunnel.com/request?from=ola&to=ole") result = JSON.parse(response.body) Now in my Node.js application, I need to retrieve values for From ...

Setting the height of a div tag in CSS/HTML5 to match the current height of the browser window

Is there a way to make the height of my div tag always equal to the height of the browser's window, so it adjusts automatically when the browser is resized? I have tried using .class { height: 100%; } But this doesn't work. I've learne ...

unable to respond when clicking an angularjs link

I'm facing an issue where I can't get a link to respond to click events in AngularJS. When I click on the anchor link, nothing happens. Here is a snippet of the AngularJS script: <script data-require="<a href="/cdn-cgi/l/email-protection" ...