What is the best approach for consuming a JSON array in AngularJS?

My goal here is to consume the JSON data that I am generating through a Spring Restful WebService. The JSON data looks like this:

[
    {
        "userid": 1,
        "firstName": "kevin",
        "lastName": "buruk",
        "email": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="c0b0b5a3b5ab80b5a2a9eea3afad">[email protected]</a>"
    },
    {
        "userid": 2,
        "firstName": "helm",
        "lastName": "krpuk",
        "email": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="0a626f666761787f7a7f614a6d676b636624696567">[email protected]</a>"
    },
    {
        "userid": 3,
        "firstName": "batok",
        "lastName": "kelapa",
        "email": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="81e3e0f5eeeaeae4ede0f1e0c1e6ece0e8edafe2eeec">[email protected]</a>"
    }
]

This JSON is being generated by a function in my Java Spring MVC Controller, which looks like this:

SpringController.java

@RestController
@RequestMapping("/service/")
public class SpringServiceController {

    UserService userService = new UserService();

    @RequestMapping(method = RequestMethod.GET,headers="Accept=application/json")
    public List<User> getAllUsers() {
        List<User> users=userService.getAllUsers();
        return users;
    }
}

I am planning to display the JSON values in an Angular table, so I have stored the JSON data in an angular object within the scope. Here is my JavaScript code named app.js:

app.js

function Hello($scope, $http) {
    $http.get('http://localhost:8080/SpringServiceJsonSample/service/').
        success(function(data) {
            $scope.users = data;
        });
}

Lastly, here is my HTML page named index.html:

<html ng-app>
<head>
<title>Angular Test</title>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.8/angular.min.js"></script>
<script src="app.js"></script>
</head>
<body>
    <div ng-controller="Hello">
    <thead>
        <tr>
            <th>ID</th>
            <th>First Name</th>
            <th>Last Name</th>
            <th>Email</th>
        </tr>
    </thead>
    <tbody>
        <tr ng-repeat="user in users">
            <td>{{user.userid}}</td>
            <td>{{user.firstName}}</td>
            <td>{{user.lastName}}</td>
            <td>{{user.email}}</td>
        </tr>
    </tbody>
    </div>
</body>
</html>

I encountered an issue where nothing was being displayed on the page. Previously, when I tried to consume JSON with only one record, it worked fine. However, now that I am trying to consume an array of records, it's not working as expected. Can you spot what might be missing here? Is it an issue with the JSON or my JavaScript implementation?

Answer №1

Make sure to update to the latest version of angular, which is currently 1.4.5. This version offers improved performance optimizations and new features.

In response to your question, there was an error in the HTML code. Here is the corrected version:

function Hello($scope, $http) {
    $scope.users = [
    {
        "userid": 1,
        "firstName": "kevin",
        "lastName": "buruk",
        "email": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="90e0e5f3e5fbd0e5f2f9bef3fffd">[email protected]</a>"
    },
    {
        "userid": 2,
        "firstName": "helm",
        "lastName": "krpuk",
        "email": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="670f020b0a0c151217120c27000a060e0b4904080a">[email protected]</a>"
    },
    {
        "userid": 3,
        "firstName": "batok",
        "lastName": "kelapa",
        "email": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="157774617a7e7e7079746574557278747c793b767a78">[email protected]</a>"
    }
]
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<body ng-app>
    <table ng-controller="Hello">
    <thead>
        <tr>
            <th>ID</th>
            <th>First Name</th>
            <th>Last Name</th>
            <th>Email</th>
        </tr>
    </thead>
    <tbody>
        <tr ng-repeat="user in users">
            <td>{{user.userid}}</td>
            <td>{{user.firstName}}</td>
            <td>{{user.lastName}}</td>
            <td>{{user.email}}</td>
        </tr>
    </tbody>
    </table>
</body>

I have resolved this issue by adding just one HTML tag for correction!

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

Disable the setTimeout() function in order to prevent the countdown from refreshing

I have a JavaScript countdown function that is working well, but I am unsure how to stop and refresh the timer to extend the time. When I call the function again before it times out, it behaves strangely by showing two countdown timers because the updateTi ...

What is the method for altering the state of a single element within a map?

As I delve into learning React, I encountered a persistent issue that has been absorbing my time for several hours now. The problem revolves around mapping an array of product sizes to buttons and controlling the state change of only the last clicked butto ...

What is the process for transitioning data between SQL, PHP, and JavaScript seamlessly?

As a developer who frequently works on SQL/PHP applications, I often find myself constantly rewriting JavaScript code to accomplish the same tasks repeatedly. When dealing with simple APIs, it's not too difficult to create one-off AJAX methods to comm ...

How can I programmatically adjust the center of a Google Maps v3 map?

I have a table with 2 columns. The first column contains a div with a Google map, while the second column has a panel that changes its width after a few seconds. On the map, there is a marker placed. Issue: When I click on a button that triggers setCente ...

What steps can I take to prevent Internet Explorer from caching my webpage?

After implementing Spring MVC for Angular JS on the front end, I encountered an issue where logging in with different user credentials resulted in incorrect details being displayed. This problem only occurred in Internet Explorer, requiring me to manually ...

Issue with VueJS components not functioning as expected with routes

I've encountered an issue when using the component tag with an id of #app within the template of my components/App.vue file. Whenever I include this setup, I receive the following errors: // components/App.vue <template> <div id="app"> ...

Is there a way to gather information from a web service and neatly display it within an HTML table?

Is it possible to fetch a JSON array from a web service and save it in a variable? Consider the following table structure: <table id="myTable" border="1"></table> The table is populated using the code below: // JSON array var myData = metho ...

Displaying localized error messages in React

Currently, I am developing a FrontEnd application using React and implementing L10n for localization. The process works smoothly for displaying static text like this: <input {...input} type="password" placeholder={strings.passwordPlaceholder} ...

Is there a way to retrieve the current object as a JSON string from inside the object using either jquery or javascript?

Looking for a way to return the current instance as a JSON text so that the values can be sent via an ajax request to a server-side script. Uncertain about where to apply the "this" keyword in a jQuery selector function Actor(){ this.input=function(pnam ...

Repairing the Performance of the 'Save' Feature

Can the 'Save' button in my code save team assignments for players selected using drag and drop? I'm considering using localStorage, but unsure about implementation. Note: To run the code properly, copy it as an HTML file on your computer. ...

AngularJS function orderBy reverses the array instead of sorting it

I encountered an issue where, after clicking the 'order button', the table does not order as expected. Instead, it reverses all the td elements. For example, 'A', 'C', 'B' becomes 'B', 'C', "A". I ...

Issues with the count up functionality in jQuery

I'm currently working on a project involving countups. My aim is to have multiple countups displayed on a single page. While having one countup using interval() function poses no issues, I encounter trouble when trying to display two or more countups ...

"What is the best way to transform tab navigation into a dropdown menu with the help

I have a collection of tabs currently on display. I am looking to transform them into a dropdown menu when the screen size changes, making them more responsive. Each set of tabs corresponds to different content. Despite trying various solutions found on s ...

Transform a collection of JSON files from the internet into a relational database within SQL Server, MySQL, or SQLITE

My team and I are currently using Teamwork, a project management tool. We have been exploring their online API which contains JSON files that can be accessed with authorization. Click here to explore the Teamwork Projects API I am interested in convert ...

Choosing an element from a multiple group listbox with jQuery

Is there a way to select items in the listbox using jQuery when dealing with optgroup elements? $('#id option[value=<?php echo $row; ?>]').attr('selected','selected'); The above code works for regular options, but how ...

Conditionally enable or disable button by comparing textbox values within a gridview using C# programming

Hey there! I'm currently diving into the world of JavaScript and C#. Feel free to correct me if you see any mistakes along the way. Check out my gridview code snippet below: <asp:GridView ID="GridView1" CssClass="table table-hover table-bordered" ...

Could there be a glitch in the angular code related to cleanliness

It seems like there might be an issue with Angular rather than my code. I'm trying to create a dynamic form using ng-repeat and encountering a problem where the form scope shows that pristine is true, even when it's not. Plunker can handle form p ...

What is the proper method for utilizing assignments instead of simply assigning values directly?

In the process of developing a markdown editor, I am currently focusing on the functionality of the B (bold) button which needs to toggle. It's important to mention that I am utilizing this library to handle highlighted text in a textarea. Below is t ...

Efficiently reducing the size of a CSS selector string with javascript

Is there a library that already performs this function? I've only been able to find online tools. The reason I am interested in accomplishing this task using JavaScript is because I need to ensure that the strings a > b, a and a> b,a are conside ...

Retrieve information from a JSON script using C#

I need to extract data from a homepage, but the information I'm looking for is embedded in a JSON script. How can I retrieve this value? For example: <div id="contentWrap"> <div id="contentTextWrap"> <div id="contentText ...