"Troubleshooting: Why is my AngularJS ng-repeat failing to

I recently started delving into AngularJS, but I've hit a roadblock with a particular issue. For some reason, the ng-repeat directive isn't iterating through the users array as expected. The resulting list is just blank.

Below is a snippet of my code:

app.js

var app = angular.module('myapp', []);

app.controller('dataCtrl', function ($scope) {
    $scope.users = [ 
        { name: 'Max', age: 20 },
        { name: 'Tom', age: 42 },
        { name: 'Alex', age: 41 },
        { name: 'Thomas', age: 3 },
        { name: 'Andreas', age: 17 },
        { name: 'Richard', age: 11 } 
    ];
});

index.html

<!DOCTYPE html>
<html ng-app="myapp" lang="de">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=no">
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
    <title>Angular JS</title>
</head>

<body>
    <div class="container">
        <h1>The Family</h1>
        <table class="table" ng-controller="dataCtrl">
            <thead>
                <tr>
                    <th>Name</th>
                    <th>Age</th>
                </tr>
            </thead>
            <tbody>
                <tr ng-repeat="user in users">
                    <td>{{user.name}}</td>
                    <td>{{user.age}}</td>
                </tr>
            </tbody>
        </table>
    </div>

    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.7/angular.min.js"></script>
    <script src="app.js"></script>
</body>
</html>

Answer №1

Make sure to remember that the correct syntax for ngRepeat is "obj in collection" and not "collection in obj". Keep it organized!

ng-repeat="user in users">

Answer №2

Absolutely, the previous responses touch upon the reasoning. I recommend exploring the "controller as" concept as you continue to learn and moving away from using $scope. It's common for introductory lessons to demonstrate ineffective approaches before presenting the correct method.

Answer №3

There seems to be a typo in your code, it should say "user" instead of "users". You can check the correction in this plunker

   <tr ng-repeat="user in users">
                    <td>{{user.name}}</td>
                    <td>{{user.age}}</td>
                </tr>

To enhance your code structure, consider using 'var vm=this' instead of $scope in your controller and implementing the 'controller as syntax' in your HTML. I have updated the plunker accordingly. Your revised HTML would look like:

  <body ng-controller="MainCtrl as vm">
    <p>Hello {{vm.name}}!</p>

    <div class="container">
        <h1>The Family</h1>
        <table class="table">
            <thead>
                <tr>
                    <th>Name</th>
                    <th>Age</th>
                </tr>
            </thead>
            <tbody>
                <tr ng-repeat="user in vm.users">
                    <td>{{user.name}}</td>
                    <td>{{user.age}}</td>
                </tr>
            </tbody>
        </table>
    </div>
  </body>

Note that 'users' has been changed to 'vm.users'.

For your app logic:

var app = angular.module('plunker', []);

app.controller('MainCtrl', function() {
  var vm = this;
  vm.name = 'World';

   vm.users = [ 
        { name: 'Max', age: 20 },
        { name: 'Tom', age: 42 },
        { name: 'Alex', age: 41 },
        { name: 'Thomas', age: 3 },
        { name: 'Andreas', age: 17 },
        { name: 'Richard', age: 11 } 
    ];
});

By utilizing these techniques, you can avoid various $scope-related issues as your codebase expands, especially with callbacks and functions. For further insights, refer to this informative article on "AngularJS's Controller As and the vm Variable" by John Papa, along with his recommended Angular style guide.

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 selecting the initial and final elements of a specific class

Here is a simple example of table markup: <div class="table"> <div class="table__headers"></div> <div class="table__row"></div> <div class="table__row"></div> </div& ...

I'm looking for a way to convert an array value to JSON using jQuery

i need assistance in converting an array value into json format. An example is provided below: Sample Array [Management Portal!@!@Production Issue Handling!@!@/IONSWeb/refDataManagement/searchDynamicScripts.do, Management Portal!@!@ Event Browser!@!@/ION ...

The function screen.getByText is not available in this context

My experience with jest and react-testing-library has been smooth for the most part, but I encountered some challenges when transitioning to the screen > getByText/etc testing method. Test describe('test the dashboard when loaded', () => { ...

AngularJS: Identifying the position (ON/OFF) of ui-switch

I'm having trouble figuring out how to identify the position of my UI switch (true/false) in my JavaScript file. Here is my HTML file with the UI switch: <ui-switch ng-model='onOff'></ui-switch> And here is my controller for t ...

Why is the 3rd argument necessary when using useReducer?

According to the information provided in the documentation: [init, the 3d argument] allows you to separate the logic for determining the initial state outside of the reducer. This is particularly useful for resetting the state later in response to an ac ...

display object issue with object display

I'm encountering a strange issue with my constructor objects in JS - when I try to view them, all I see is [object Object]. Can anyone help me figure out why this is happening? Check out the code snippet on MyCodeFiddle. ...

Is there a way to incorporate HTML code into a fullCalendar 4 event title?

Is it possible to add HTML content to an event title using eventRender in FullCalendar version 4? document.addEventListener('DOMContentLoaded', function() { var calendarEl = document.getElementById('calendar'); var calendar = new ...

Using JavaScript and HTML, create a click event that triggers a drop-down text

Can anyone help me with creating a dropdown feature using JavaScript, HTML, and CSS? I want to be able to click on the name of a project and have information about that project show up. Any suggestions on how I can achieve this? Thanks in advance! ...

Is AngularJS more than just a view?

My goal is to create a single-page Angular app with a central view surrounded by tools like a sidebar and top bar. However, when the user is not logged in, I want the view to display a login partial while hiding the side- and top bars. Additionally, ther ...

From SketchUp to Canvas

I've been trying to figure out how to display a 3D model created in SketchUp on a web page. After discovering three.js and exporting the model to a .dae file for use with ColladaLoader, I still can't get it to appear on my canvas. (I'm using ...

What is the best way to extract the values associated with keys using a data variable?

I need help accessing the values of the keys under the containertransport in my nuxt.js project using the data variable url. If I try to access it like {{item.containertransport}}, it works fine. <template> <div> <p class="p_1" v-f ...

Display data when clicking on Tailwind

I am currently displaying a sub menu on hover using Tailwind CSS. However, I am wondering how I can achieve the exact same functionality by triggering an onclick event instead of hovering over the menu. Here is a DEMO showcasing the current setup. CODE: ...

AngularJS: steer clear of relying on the 'angular' global variable

Is it advisable to refrain from using the 'angular' global object within Controllers, Services, etc? Suppose we want to call the function: angular.isDefined(myVar) How should we reference the 'angular' object? Possible approaches: ...

What is the best way to show input choices once an option has been chosen from the 'select class' dropdown menu?

When it comes to displaying different options based on user selection, the following HTML code is what I've been using: <select class="form-control input-lg" style="text-align:center"> <option value="type">-- Select a Type --</opti ...

HighCharts: visualize vertical stacked bars displaying the distribution of percentages within each stack

I currently have a stacked bar chart similar to the one shown in this JSFiddle demo. My goal is to transform the stacks so that each bar represents a percentage of the total stack height. For instance, in the Apples stack we currently have values {3, 2, 5 ...

Cannot find property in type, and the parameter is implicitly of an unspecified type

I've been encountering this issue where I keep getting an error message. I attempted to resolve it by setting "noImplicitAny": false in tsconfig.json, but unfortunately that did not work. As for the 'Property does not exist on type' error, I ...

Avoid repeatedly invoking an API within a loop

Is there a way to continuously call an API every 2 seconds within a loop? var itemArray = ['apple', 'banana', 'orange']; for (var i = 0; i < itemArray.length; i++) { $timeout(makeApiCall(itemArray[i]), 2000); } functi ...

Partially Assessed Ajax Response

I am struggling with my ajax response as it seems to evaluate only some of the html, but not all of it. For instance, I have this code that replaces a div with the response from the request: eval(document.getElementById("test").innerHTML-xmlhttp.response ...

The tooltip being displayed is plain and lacks any design elements

When I hover over my a element, only a simple tooltip appears without any styling, unlike what is shown in the Bootstrap documentation. (I am creating the a element using JavaScript) HTML <!DOCTYPE html> <html lang="en"> <head> ...

Guide to displaying the output of a JS calculation in a Bootstrap modal dialog box

I have a HTML and JavaScript code that determines the ideal surfboard for the user based on their input data (style, experience, height, weight) and displays the recommended surfboard type. Here is the initial code snippet I attempted to use: function c ...