Having trouble creating a table using a JSON object in AngularJS

Click here to view the converted JSON object

Please pay close attention to my question

Hello, in the code below I am attempting to convert XML data into a JSON object. With this converted JSON object, I am aiming to create a table using AngularJS. The issue arises when trying to load individual attributes of the JSON object such as {{employee.EmpId}}. Upon observation, I noticed that when theconverted JSON object is directly assigned:

$scope.Employees = { "Employee": [ {"EmpId": "4", "Name": "Chris", ... 

The output aligns with my expectations. However, when I assign it as follows:

i.e., $scope.Employees = response.data; It does not work as expected. What might be causing this issue? Here, 'response.data' represents the result obtained from the success function.

Click here for the converted JSON object

https://i.sstatic.net/nwZ6a.png https://i.sstatic.net/shkh3.png

Answer №1

Take a look at this straightforward example that makes use of the provided json data:

HTML

<html xmlns="http://www.w3.org/1999/xhtml" ng-app="myApp">
<head runat="server">
    <title></title>
</head>
<body ng-controller="myController">
    <div>
        <table>
            <thead>
                <tr>
                    <th>EmpId</th>
                    <th>Name</th>
                    <th>Sex</th>
                    <th>Phone</th>
                    <th>Address</th>
                </tr>
            </thead>
            <tbody>
                <tr ng-repeat="employee in json.Employee">
                    <td>{{employee.EmpId}}</td>
                    <td>{{employee.Name}}</td>
                    <td>{{employee.Sex}}</td>
                    <td>{{employee.Phone[0].__text}}</td>
                    <td>{{employee.Address.Street}}</td>
                </tr>
            </tbody>
        </table>
    </div>
    <script src="scripts/angular.js"></script>
    <script src="scripts/app.js"></script>
</body>
</html>

JavaScript

(function () {
    angular.module('myApp', [])

    .controller('myController', function ($scope) {

        $scope.json = { "Employee": [{ "EmpId": "4", "Name": "Chris", "Sex": "Male", "Phone": [{ "_Type": "Home", "__text": "564-555-0122" }, { "_Type": "Work", "__text": "442-555-0154" }], "Address": { "Street": "124 Kutbay", "City": "Montara", "State": "CA", "Zip": "94037", "Country": "USA" } }] };


    })

}());

Answer №2

Make the following adjustments to your code.

<div ng-app><div ng-controller="httpController">
  <div>
    <table>
      <tr ng-repeat="employee in Employees.Employee">
        <td>{{employee.EmpId}}</td>
        <td>{{employee.Name}}</td>
        <td>{{employee.Phone._Type}}</td>
        <td>{{employee.Phone.__text}}</td>
        <td>{{employee.Address.Street}}</td>
        <td>{{employee.Address.State}}</td>
        <td>{{employee.Phone.Zip}}</td>
        <td>{{employee.Phone._text}}</td>
        <td>{{employee.Address.Country}}</td>

      </tr>
    </table>
  </div>

Answer №3

Your code has a secondary problem that needs attention. The response data can be found within response.data. Therefore, in addition to verifying the validity of your JSON, you must implement the following statement:

$scope.Workers = response.data

Answer №4

Additional note following my previous response regarding response.data. I haven't found the correct solution for your JSON object yet, so here is a comprehensive answer:

When using ng-repeat, it requires a list of items to iterate over. You need to remove the surrounding 'Employee' wrapper from your JSON, like this:

$scope.Employees = [
                     {"EmpId": "4", "Name": "Chris", "Sex": "Male", "Phone": [ { "_Type": "Home", "__text": "564-555-0122" }, { "_Type": "Work", "__text": "442-555-0154" } ], "Address": { "Street": "124 Kutbay", "City": "Montara", "State": "CA", "Zip": "94037", "Country": "USA" } },
                     {"EmpId": "5", "Name": "Chris", "Sex": "Male", "Phone": [ { "_Type": "Home", "__text": "564-555-0122" }, { "_Type": "Work", "__text": "442-555-0154" } ], "Address": { "Street": "124 Kutbay", "City": "Montara", "State": "CA", "Zip": "94037", "Country": "USA" } }
                   ]

(I've included an additional Employee with ID 5 in the example above, but even one employee would suffice as long as they are enclosed within a list ([]).

You can utilize the following code with this JSON object:

 <tr ng-repeat="employee in Employees">
     <td>{{ employee.EmpId }}</td>
     <td>{{ employee.Name }}</td>
     <td>etc ...</td>
 </tr>

Ensure that your JSON follows this structure, with comma-separated objects within a list.

Retrieve data in this JSON format from your get request, and remember to extract data from response.data rather than response.

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

Tips for querying MongoDB schemas that reference other schemas in the field?

Looking to search for a product by its name within the DOC Schema. However, the products are stored as references in another Product Schema with the _id. Below you can find the code snippets to understand the structure: DOC Schema import mongoose from &qu ...

What is the best way to bind a model to a directive in Angular.js?

I have been experimenting with different methods to create a two-way binding between my directive and repeater, but so far I haven't been successful. Although I have tried various strategies suggested online, the current setup does not pass item.myDat ...

"How to troubleshoot installation errors when installing Angular on Ubuntu using

Hi there, I'm just beginning to dive into learning Angular. However, I've encountered an issue while trying to install Angular using npm install angular on my Ubuntu 16.04LTS system. The error message that pops up is as follows: npm ERR! Linux 4 ...

Converting XML to JSON with the help of XSLT transformation

I am currently working on a project that involves converting XML to JSON using XSLT. Here is a snippet of the XML I am trying to convert: <some_xml> <a> <b> <c foo="bar1"> <listing n="1">a</listing> <list ...

The function .then is not compatible with AngularJS

I have a service that is responsible for loading data. angular.module('App').service('daysService', ['$http','$q',function($http,$q) { var days = []; return { loadDay: function() { ...

What is the best way to select and link a specific section of a string using Javascript?

I have a JavaScript string that looks like the following: const pageContent = "He stood up and asked the teacher, "Can you elaborate the last point please?"; My goal is to map out the words in the string and display them in a way that makes ...

Tips for utilizing a variable selector with jQuery's .attr() method

In a jQuery DataTable, there is a scenario where some values can be modified by clicking an edit button. When clicked, a modal popup appears with a form to enter new values for notes and status: ... "columnDefs": [ { ...

use the fetch api to send a url variable

I'm struggling to pass a URL variable through the API fetch and I can't seem to retrieve any results. As a newcomer to Javascript, any help is greatly appreciated. //Get IP address fetch('https://extreme-ip-lookup.com/json/') .then(( ...

Encountering an ELIFECYCLE error in Usemin while attempting to target multiple HTML files

Currently enrolled in a Coursera course titled "Front-End Web UI Frameworks and Tools: Bootstrap 4," I have encountered an issue with NPM scripts. While trying to create scripts in my package.json file to minimize files and move them to a distribution fold ...

Creating a Form Layout with Bootstrap - Organizing Text Boxes and Text Areas

https://i.sstatic.net/oqRwR.jpg In the image above, I need to adjust the position of the textbox to align it with the TextArea. Is there a Bootstrap class that can help me achieve this? My current version of Bootstrap is 3.3.6. HTML &l ...

Enhancing your JQuery Select2 plugin by incorporating a Checkbox feature

I am currently utilizing the jQuery select2 plugin to enable multiple selections. My goal is to incorporate a checkbox for each selectable option. Depending on whether the checkbox is checked or unchecked, the dropdown option should be selected accordingl ...

Guide on transferring Vue form input data to Adonis controller through an http request

I have a Vue component that prompts the user to enter their email address. I've utilized v-model for data binding. <template> <input v-model="email" type="text" placeholder="Email" /> <button class="tiny">Send</button> ...

Displaying a URL inside a div upon clicking a specified href link in an Angular application

After hours of searching on various search engines, I am still unable to find the solution to my problem. My goal is to display the URL in a div once it has been clicked using $http for dynamic links. Here's an example of what I'm trying to achi ...

Converting a string to JSON format in the presence of a JSON payload enclosed within another JSON wrapper

I have a JSON string that consists of both a JSON wrapper and a JSON payload nested within. In order to improve readability, I am looking for a way to beautify the string. Although I have tried various regular beautifiers (such as Newtonsoft, and one fro ...

Display an assortment of various categories once every other time

As a novice AngularJS user, I am looking to showcase a collection in my HTML code using a specific directive: displaying items alternately on the left and right side. For example, the first item on the left, the second on the right, the third on the left, ...

What is the best way to centrally align a Card while keeping the text left-aligned?

New to coding and need some guidance. I'm attempting to create a card that is not the full width of the window. I have specified a cardStyle as shown below. cardStyle:{ width: '95vw' align? : 'center?' textAlign? : &a ...

What is the best way to insert a JsonObject into a JsonArray that I need?

Can someone help me understand how to add data to a JSON array with specific headers like shown in the right hand side of this picture? https://i.sstatic.net/fkPyS.png I have code that can only add two JSON objects, like on the left hand side. What addit ...

Get the name of the array using JavaScript

Here is an example of my situation: var list1 = ['apple', 'banana', 'orange']; var list2 = ['carrot', 'lettuce', 'tomato']; When I use: alert(list1) I get: apple, banana, orange. This is corre ...

What is the method for transforming a string containing the name of an array into a format that can be displayed in a Vue.js template?

<b-card v-for='callType in callTypes' no-body class="mb-1"> <b-table striped hover :items="{{callType.lineType}}"> </b-table> </b-card> When each callType is the name of an array. callTypes: [m ...

"Unlocking the secret to fetching the id of the clicked element within a Highchart context menu

Is it possible to retrieve the id of a clicked button on the highchart context menu? Alternatively, is there a way to execute the click function twice? const contextButtonArray = []; contextButtonArray.push({ { text: 'TEST BUTTON&ap ...