Display issue with AngularJS: Text and data not appearing

Currently, I am in the process of creating a simple Angular application to enhance my skills. In this app, a list of users is loaded and displayed on the homepage with checkboxes next to each name. Additionally, the number of active users is shown.

The user list functionality seems to be working fine as I have 11 users listed with corresponding checkboxes. However, the actual user names do not appear. The users.length variable also appears empty.

Below is my core.js file:

var userApp = angular.module('userApp', []);
userApp.controller("mainController", mainController);

function mainController($scope, $http) {
    $scope.formData = [];

    // Retrieve all users upon page load
    $http.get('/api/users')
        .success(function(data) {
            $scope.users = data;
            console.log(data);
            console.log(data.length);
        })
        .error(function(data) {
            console.log('Error: ' + data);
        });


    // Add new user via API upon form submission
    $scope.createUser = function() {
        $http.post('/api/users', $scope.formData)
            .success(function(data) {
                $scope.formData = {}; 
                $scope.users = data;
                console.log(data);
            })
            .error(function(data) {
                console.log('Error: ' + data);
            });
    };

}

And here's my index.html code snippet:

<html ng-app="userApp">
<head>
    <title>Node/Angular Todo App</title>

    <link rel="stylesheet" href="//netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap.min.css">
    
    <script src="//ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script>
    <script src="//ajax.googleapis.com/ajax/libs/angularjs/1.0.8/angular.min.js"></script>
    <script src="core.js"></script>

</head>

<body ng-controller="mainController">

    <div class="container">
        <div class="jumbotron text-center">
            <h1>Users Count: <span class="label label-info"> {{ users.length }}</span></h1>
        </div>

        <div id="user-list" class="row">
            <div class="col-sm-4 col-sm-offset-4">
                <div class="checkbox" ng-repeat="user in users">
                    <label>
                        <input type="checkbox">{{ user.first_name }}
                    </label>
                </div>
            </div>
        </div>

        <div id="user-form" class="row">
            <div class="col-sm-8 col-sm-offset-2 text-center">
                <form>
                    <div class="form-group">
                        <input type="text" class="form-control input-lg text-center" placeholder="Enter username" ng-model="formData.text">
                    </div>
                    <button type="submit" class="btn btn-primary btn-lg" ng-click="createUser()">Add</button>
                </form>
            </div>
        </div>
    </div>

</body>

</html>

Example user record:

{
"id": 1,
"first_name": "Bruce",
"last_name": "Lee",
"email": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="e587898080a58088848c89cb868a88">[email protected]</a>",
"password": "blee",
"created_at": "2016-01-08T21:49:18.337Z",
"updated_at": "2016-01-08T21:49:18.337Z"
},

While the data is successfully logged in the console, I'm facing issues with displaying the user information properly.

If anyone can lend a hand, it would be greatly appreciated!

Thank you! 🙏

Answer №1

To migrate user data to Angular, ensure you update {{ first_name }} to {{ user.first_name }} in your HTML code.

This indicates that each label should fetch the name from the specific user object, not a global declaration.


Additionally, make sure to properly register the controller in your JavaScript code.

Add this to your core.js

userApp.controller("mainController", mainController);

Answer №2

Angular's $http service is designed to return a response object rather than raw data. This response object contains various properties as outlined in the documentation:

The response object includes the following properties:

data – {string|Object} – Transformed response body using transform functions.

status – {number} – HTTP status code of the response.

headers – {function([headerName])} – Function to retrieve headers.

config – {Object} – Configuration object used for the request.

statusText – {string} – HTTP status text of the response.

To assign the value of data.data to the $scope.users variable, you can use the following code snippet:

$http.get('/api/users')
    .success(function(data) {
        $scope.users = data.data; // <-------- here!!! (consider calling it response so you can use 'response.data'
        console.log(data);
        console.log(data.length);
    })
    .error(function(data) {
        console.log('Error: ' + data);
    });

Quick note: It appears that you are still utilizing the outdated methods (.success and .error). Instead, the service now returns a promise which should be handled using .then.

For example

$http
    .get('/api/users')
    .then(function(response) {
        $scope.users = response.data;
    }, function(error) {
        console.log('Error: ' + error);
    });

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

How to display JSON containing nested objects in AngularJS using the ng-repeat directive

Hey everyone, I have this JSON external file that I need help with: { "success":true, "errors":[ ], "objects":[ { "cod":"8211300", "descricao":"Serviços advocatícios" }, // more objects here... ] } In ...

The class .is-invalid transforms into .is-valid when rendered

Currently, I am incorporating bootstrap into my react project. In this case, I have a variable called mobile that needs to undergo validation whenever there is a change in the input field. Below is the code snippet for the component: const EnterMobile = ( ...

Looking to Add Dynamic Website Embed Link?

When a user arrives at the website and the Current Top URL is "https://website.com/?code=https://webbbb.com", I need to dynamically set the iframe URL to "https://webbbb.com" for embedding purposes. This way, I can automatically link my complete other web ...

"Encountering a hiccup with Axios while making a GET request in a React

I've been attempting to retrieve data from the API using an axios get request, but I keep encountering an error. The error message reads as TypeError: this.setstate is not a function. Despite looking at various solutions for similar issues, most of th ...

Ensuring object validity using a mongoose query

Looking to validate an object using a mongoose query. Let's say we have the following object: const user = {username: 'foo', email: 'foo@mail', type: 2}; and this mongoose query: const query = { type: { '$in': [ 2, 1 ...

Stopping Android WebView from navigating

Currently, I am working with Android version 5.0 and the latest update of the WebView component. My goal is to embed a remote website into a WebView without making any modifications to the source code of this website. Here is the code snippet that I have ...

Prevent users from tabbing to the next input field in a web form

Is it possible to prevent users from using the tab button on their keyboard to navigate to the next field in a form? <form action="/action_page.php"> First name:<br> <input type="text" name="firstname"> <br> Last name:< ...

Remove a record from the EntityFramework database using ajax

I am a beginner and facing an issue with deleting records from the database using JavaScript, Ajax, and Json in MVC Entity Framework. My delete button seems to be malfunctioning. In my controller class, the action code is as follows: public ActionResult ...

What is the process for retrieving a list of image URLs from Firebase storage and then transferring them to Cloud Firestore?

Currently, I am working on uploading multiple images to Firebase Cloud Storage simultaneously. The process involves uploading the images, obtaining their URLs upon completion, adding these URLs to a list variable called urlsList, and then uploading this li ...

Unable to configure Angular UI Date Picker for selecting only the week

In this coding scenario, my goal is to utilize angular-ui-datepicker as a Week Picker. However, I am encountering difficulties as the only options available are normal date picker, month picker, or year picker; whereas, I specifically need a week picker. ...

Three.js is currently rendering a blank canvas in pure white

After following the tutorial at , my browser only displays a white window. I attempted separating the files into js and html, but no luck. What I have already tried: experimenting with adding/deleting the nomodule parameter in the script tag utilizing a ...

Positioning a video within a sphere using Three.js

Currently, I am utilizing Three.js to implement a video display where users can navigate through the video using their mouse. You can see an example of this functionality here: You can find the code for this project here: https://github.com/mrdoob/three.j ...

What is the purpose of enclosing an Angular app within a function?

As I delve into learning Angular, I've encountered a recurring snippet in the app.js file across various resources: (function () { \\\myAngularModules })(); Despite its prevalence, the explanation provided is often just ...

Are external JavaScript files cached in the same manner as images?

Is it possible for a single pagehandler script to be called from the browser cache when navigating between multiple pages that refer to it? ...

How to tell if one mesh is contained within another in Three.js

Currently, I am experimenting with Three.js and trying to figure out a way to check if one mesh is completely contained within another mesh. I've created a small robot that moves around inside a home box controlled by the player. While I know how to d ...

Encountering permission issues while attempting to add `@nuxtjs/sentry` in a Docker container running Node 16.14. Installation

While attempting to add @nuxtjs/sentry to my project by running npm install @nuxtjs/sentry, I encountered some issues. Here is the error message I received: npm ERR! code 1 npm ERR! path /app/node_modules/@sentry/cli npm ERR! command failed npm ERR! comm ...

arranging an array in JavaScript that contains numeric values stored as text

I'm attempting to organize my array. My goal is to sort the elements based on the value within the square brackets at index 2. This means that the element at position 15 should be at the top, followed by the one at position 8 and so forth. I've ...

Node.js: The object is not defined in the response object

I'm struggling with a simple function that I've defined below function upload(response, postData) { console.log("Received: " + postData); response.writeHead(200,{"Content-Type":"text/plain"}); response.write("You've sent text: " ...

An error has been caught in the console stating that an undefined function is not recognized

Encountering a console error (Uncaught TypeError: undefined is not a function) on line 156 upon loading and unable to resolve it. Provided below is the line causing the issue along with its full context. Also included is the site link for reference. Any he ...

Exploring React components - comparing mount and shallow rendering techniques and practicing event simulation

Recently, I've been delving into testing React components and have encountered a challenge. Specifically, I am striving to simulate entry into the input field identified as 'componentCount' in my code. My experience with React spans less tha ...