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

The Node.js application that uses Express and connects to a MSSQL database is reporting that the database

One of my other applications utilizes express and routes, but for this new app I wanted to simplify it. Despite being confident in the correctness of the connection string, I encountered an issue. script.getQuestions(connection); script.getQuestions = fu ...

What is the process for comparing two objects in TypeScript?

There is a unique class named tax. export class tax { private _id: string; private _name: string; private _percentage: number; constructor(id: string = "", taxName: string = "", percentage: number = 0) { thi ...

Tips for efficiently deconstructing JSON arrays, objects, and nested arrays

I'm attempting to destructure a JSON file with the following structure: [ { "Bags": [ { "id": 1, "name": "Michael Kors Bag", "price": 235, "imgURL" ...

Validating numbers in React JS input fields component

I need assistance with implementing number validation for 3 Textfields in my application. Currently, the code displays an error message if a Textfield is empty, but I am stuck on validating whether the input is text or numbers. import React from 'rea ...

AngularJS/Ionic: Issue with HTTP GET requests not completing within a specified timeframe

Attempting to populate options with specific values instead of undefined, but encountering a delay in retrieving the values after the select box has finished loading. https://i.stack.imgur.com/SpEFP.jpg To illustrate, here is the HTML code snippet: < ...

How can I utilize jQuery to add tags in a box?

I have an idea for a feature similar to the Stack Overflow tag insert. My goal is to have a box where I can type in a tag, click 'Add', and see it appear above. Additionally, I want this action to update an array called 'SelectedTags'. ...

Exploring JSON data with Apache NiFi using the EvaluateJsonPath and Split

Using the ConvertRecord processor, I successfully converted a csv text file to a json file with the following structure: [ {"A":1001,"B":"20170101","C":0.3}, {"A":1001,"B":"20170102","C":0.1}, .....] In an attempt to retrieve certain paths fro ...

Exploring the challenges of setting up Node in an attempt to unravel AngularJs 1.5

I recently started reading a book called "Unraveling AngularJS 1.5" in order to expand my knowledge on Angular development. Early on in the book, the author suggests installing Node.js, so I went ahead and did that. When I ran Node on the command prompt, i ...

The type 'Observable<any>' cannot be assigned to the type 'Observable<T>'

Here is the code I am working with: import {HttpClient} from '@ngular/common/http'; private httpClient: HttpClient; do_request(method: string, url: string, ...

Unlocking the WiFi Security Key and Accessing Connected Devices with Javascript

When utilizing the command line netsh wlan show interfaces, it displays various information. However, I am specifically interested in extracting the data Profile : 3MobileWiFi-3D71. My goal is to retrieve only the content after the : so that ...

import jQuery into a JavaScript file

I'm currently working on a Chrome extension that relies on background.js to perform basic tasks. I need to include jquery.js in my background.js file so that I can utilize its ajax function, but I'm unsure of how to achieve this. Is it even possi ...

Protractor's direct entryway to the factory

Greetings, I am the owner of a small factory called myFactory in my application: .factory('myFactory', ['$q', function ($q) { function myMethod() { ..... } return { myMethod: myMethod }; }]); ...

Customize variable values on-the-fly in Laravel

I am trying to create a navbar in Laravel with Vue.js as a blade.php file. I want to include a variable like {{xyz}} in the navbar, and when I navigate to another page, be able to set text using Vue.js or something similar. Can someone assist me with this? ...

Highlight and trim lengthy text using React

Imagine I have a lengthy text: Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo con ...

Is it possible to dynamically add elements in AngularJS without relying on directives?

As a newcomer to Angularjs and not very fluent in English, I embarked on the journey of adding <li> using directives. You can see the result of my first attempt at this link. Next on my list was mastering two-way binding by passing values between th ...

AngularJS - retrieving and displaying the selected value from an HTML dropdown menu

Could someone help me figure out why the Land selection is empty when trying to display it as {{ selectCenter.land }}? For reference, here is a functional plunker: http://plnkr.co/edit/Q8jhdJltlh14oBBLeHJ9?p=preview And the relevant code snippet: ...

Keep your data safe and protected within a Node CLI application

Currently developing a NodeJS command-line application that interacts with an API to provide data to users. To access the public API, users need an API token. The CLI will be globally installed on users' machines using npm i -g super-cool-api-cli. Up ...

Is it considered acceptable to retrieve the action payload in mapDispatchToProps in a React/Redux setup?

In my MediaUpload component, I have a mapDispatchToProps function that handles file uploads. When a file is added, the onChange handler triggers two actions: creating new media entries for the files and updating the form data in the state with the generate ...

Choose to either push as a single object or as individual items

I have a quick question that I'd like to get some clarity on. Can someone explain the distinction between these two code snippets: export const addToCart = function(product, quantity){ cart.push({product, quantity}); console.log(`${quantity} ...

Is it allowed to use an ID as a variable identifier?

One method I often use is assigning a variable with the same name as the id of an element, like this: randomDiv = document.getElementById("randomDiv"); randomDiv.onclick = function(){ /* Do something here; */ } randomDiv.property = "value"; This tech ...