Having trouble creating an angularjs table using ng-repeat in the controller?

I have a sample snippet that I would like to discuss. My goal is to display a JSON object in an angular table using ng-repeat, which is being generated from my angular controller script. I have attempted the code below, but for some reason, the table is not generating and its data isn't displaying. Please help me identify the issue. You can view the Fiddle here.

I am aiming for an output similar to:

Text  IND   US    UK    AUS
No    100   200   170   50 

This is the HTML structure:

<div ng-controller="TestCtrl">   
</div>

And here is the app.js content:

var testmodule = angular.module('myModule', []);
testmodule.controller('TestCtrl', function ($scope) {
  $scope.mydata =  [{
    "a": ["IND", "US", "UK", "AUS"],
    "b": ["100", "200", "170", "50"],
    "c": "Text",
    "d": "No",
}];

var mytable= angular.element(' <div class="table-responsive"> <table class="table" ng-repeat="item in mydata track by $index"> <thead> <tr> <td>{{item.c}}</td><td ng-repeat="c1 in item.a track by $index">{{c1}}</td></tr></thead> <tbody> <tr> <td>{{p.d}}</td><td ng-repeat="d1 in p.b track by $index">{{d1}}</td></tr></tbody> </table> </div>');
console.log("mytable: "+JSON.stringify(mytable));
});

Answer №1

To improve the code, it would be better to place the HTML on the html page instead of embedding it in the controller. Also, when accessing p.d and p.b, remember that these fields are within the item object from your ng-repeat directive, so the correct way to access them is item.d and item.b. Here's an updated version that should work:

HTML:

<div ng-controller="TestCtrl">   
  <div class="table-responsive"> 
      <table class="table" ng-repeat="item in mydata track by $index"> 
        <thead> 
          <tr> 
            <td>{{item.c}}</td>
            <td ng-repeat="c1 in item.a track by $index">{{c1}}</td>
          </tr>
        </thead> 
        <tbody> 
          <tr> 
            <td>{{item.d}}</td>
            <td ng-repeat="d1 in item.b track by $index">{{d1}}</td>
          </tr>
        </tbody> 
      </table>
  </div>
</div>

JavaScript:

var testmodule = angular.module('myModule', []);
testmodule.controller('TestCtrl', function ($scope) {
  $scope.mydata =  [{
    "a": ["IND", "US", "UK", "AUS"],
    "b": ["100", "200", "170", "50"],
    "c": "Text",
    "d": "No",
   }];

});

Working Plunker: HERE

-

UPDATE: It appears that you want to output your Angular element to the console. Please note that mytable is an Angular element, not a JSON object, so you won't be able to stringify it...

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 there a way to ensure that my function does not return undefined and instead returns a specific value?

Currently, I am facing a roadblock while attempting to conquer the Rock-Paper-Scissors challenge proposed by The Odin Project. Some confusion arises as my function playRound seems to be returning undefined when executed. Any insights or assistance in res ...

methods to add an object to formData in vuejs

I am having trouble appending an object to FormData using Axios. I do not want to send data by JSON.stringify() data () { return { product: { title: '', description: '', properties: { ...

Extract form input to utilize in nodemailer

Currently I am working on a form implementation where I intend to utilize nodemailer for sending test emails to myself. My goal is to have the email inputted into the form dynamically appear in both the "to" and "subject" fields when the user submits the f ...

Guidelines for creating animation for a single point in SVG Polygon

Is there a way to animate the movement of a single polygon point within an SVG using velocity.js? Your assistance is greatly appreciated! <p>Changing...</p> <svg height="250" width="500"> <polygon points="0,0 200,0 200,200 00,20 ...

Encountered an issue with launching Chrome in Puppeteer for Node.js

My code was uploaded to EC2 AWS, but unfortunately it is not working properly after the upload. Interestingly, it runs correctly on localhost. Despite trying various solutions, I am still facing this issue. Any suggestions on the correct approach to resolv ...

Creating sequential numbers using jQuery

Recently, I worked on a script (credit to Chyno Deluxe) that generates a list of menu items based on what is written in the input box. However, I now have a new requirement which involves generating a sequence of numbers to be added continuously. Here is ...

Error occurs in React Native when trying to import routes due to type mismatch

My react native app is running on my physical device, but I encountered an error when importing routesContainer in my app.js. Can anyone shed some light on why this error is occurring? TypeError: Super expression must either be null or a function [Mon Oct ...

How to merge text (string) with date in HTML using JavaScript

I am attempting to blend a day with the phrase "this is the day" in HTML. I gave it a shot, but the concatenation didn't work as expected. ...

unorthodox method of transmitting parameters within express.js source code

While searching for the source code of express router, I came across this interesting piece: var debug = require('debug')('express:router:route'); I am curious to know more about this unusual way of passing arguments. Can someone ...

Unable to update the scope upon $emit in the component

In my AngularJS component, I have a value stored in the scope that provides a URL to an <img> element in the view. Whenever a user changes the image, the controller emits a change using $rootScope.$emit, causing the URL value to update. Ideally, the ...

What is the best way to extract text/html that appears between two consecutive <input> tags?

Is there a straightforward method to extract the text or HTML content located between input tags, even though these tags do not require closing tags? For instance, in the example below, I am looking to retrieve <b>Bob and Tim</b><br>Tim & ...

What is the best way to delay an observable from triggering the next event?

In my Angular project, I am implementing RxJs with two subjects. s1.next() s1.subscribe(() => { // perform some operation and then trigger the event for s2 s2.next() }); s2.subscribe(() => { // perform some operat ...

How can I enable pagination in Datatables when the table HTML is generated using Angular after the drawCallBack function?

Below is the drawCallBack function I have implemented: "fnDrawCallback": function( oSettings ) { console.log("dt redrawn"); var selector = $("#example_table"); console.log(selector); function recompileForAn ...

Checkbox not appearing in datagrid when using Material-UI

There are some key code snippets related to the datagrid below const apiRef = React.useRef(null); const [gotApiRef, setGotApiRef] = useState(false); const [gotApiRef2, setGotApiRef2] = useState(false); console.log("apiRef.current: ", apiR ...

Progression from Angular2-rc1 to Angular2-rc2 encounters TypeScript error: anticipating ',' (TS1005)

Encountering an issue with upgrading Angular2 from RC1 to RC2, following exception is being thrown: Here's my main.ts file, I haven't made any changes to it during the upgrade process. Line 13 is where the bootstrap method is called. import {pr ...

A single snippet of JavaScript blocking the loading of another script

I've encountered an issue where the code seems to be conflicting with itself. The top part works fine, but the bottom part doesn't. However, when I remove the top portion, everything works as intended! You can see a working example of both compo ...

Tips for ensuring that a JavaScript program does not get blocked by other API calls

My JavaScript API currently has limitations that prevent other APIs from being called or allowing the API to call itself while running. The API involves sleeping for a specific duration, during which I would like other API calls to be made as well. I have ...

The differences between using the opacity attribute in HTML and the opacity property

There are two distinct methods for adjusting opacity in HTML: <div opacity="0.5"></div> and <div style="opacity: 0.5;"></div> I am familiar with setting these values in JavaScript as well: div.setAttribute("opacity", 0.5); and ...

The tab indicator in Material-UI fails to update when the back button is clicked

My code is currently functioning well: The tab indicator moves according to the URL of my tab. However, there is a peculiar issue that arises when the back button of the browser is pressed - the URL changes but the indicator remains on the same tab as befo ...

Congratulations! Your product has been successfully added to Magento using Ajax

While using Firebug, I discovered that JSON generates a message within the success function. However, I am having trouble figuring out how to display it. As a workaround, I attempted to add the following code snippet: if(data.status == 'ERROR'){ ...