"Troubleshooting: Issue with AngularJS ng-repeat not functioning properly when using an

I am working with a simple list

<ul>
    <li ng-repeat="spiel in spielListe">Do something</li>
</ul>

Along with a perfectly connected controller

$scope.spielListe = [];

There is also a method that adds objects to the array in this format:

var spielObjekt = {team1: "Teamname 1", team2: "Teamname 2", court: ""};
$scope.spielListe.push(spielObjekt);

As a result, the array appears like this:

https://i.sstatic.net/tUTFu.png

The specific content of the objects is not essential. The goal is for Angular to run the ng-repeat twice and display my text twice - however, the HTML page remains blank.

What mistake might I be making? Where could an error occur?

Update

It seems there is an issue with the .push function. I added one object with the same structure to my array, which displays correctly in the ng-repeat. However, the two objects pushed in later are not being shown. Is this a problem?

Update 2

Thank you for your assistance - it turns out the mistake was having multiple elements in the DOM with ng-controller="contentCtrl" declared within them. This caused the controller to be called multiple times and resulted in the objects not displaying as expected.

Answer №1

There seems to be some ambiguity in the provided data. Based on your query, it appears you are interested in one of the following scenarios:

Scenario 1

If you expect your object to look like

{team1: "Teamname 1", team2: "Teamname 2", court: ""}
, then this will only display once in the output as it is a single object.

Here is an example for the above situation:

<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>

<body>

    <div ng-app="myApp" ng-controller="MyCtrl">
        <ul>
            <li ng-repeat="spiel in spielListe">{{spiel.team1}}</li>
        </ul>
        <button ng-click="addItems()">Add</button>
    </div>

    <script>
        var app = angular.module('myApp', []);
        app.controller('MyCtrl', function ($scope, $http) {
            $scope.spielListe = [];
            $scope.addItems = function () {

                var spielObjekt = {
                    team1: "Teamname 1",
                    team2: "Teamname 2",
                    court: ""
                };
                $scope.spielListe.push(spielObjekt);
            }
        });
    </script>

</body>

</html>

Scenario 2

However, if you wish to have this displayed three times in your output, you will need to adjust the JSON structure as follows:

["Teamname 1", "Teamname 2", ""]

and use ng-repeat as shown below:

<li ng-repeat="spiel in spielListe">{{spiel}}</li>

or modify the JSON structure like this:

[{TeamName: "Teamname 1"}, {TeamName: "Teamname 2"}, {TeamName: ""}]

and use ng-repeat as:

<li ng-repeat="spiel in spielListe">{{spiel.TeamName}}</li>

This is because looping can only be done through an array of objects and not a single object. Here is an example showcasing this implementation.

<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>

<body>

    <div ng-app="myApp" ng-controller="MyCtrl">
        <ul>
            <li ng-repeat="spiel in spielListe">{{spiel}}</li>
        </ul>
        <button ng-click="addItems()">Add</button>
    </div>

    <script>
        var app = angular.module('myApp', []);
        app.controller('MyCtrl', function ($scope, $http) {
            $scope.spielListe = [];
            $scope.addItems = function () {

                var spielObjekt = [
                    "Teamname 1", "Teamname 2", ""
                ];
                $scope.spielListe = $scope.spielListe.concat(spielObjekt);
            }
        });
    </script>

</body>

</html>

Answer №2

Your spielObjekt variable represents just one object, so when you push that object into an array, your <li> element will only appear once. Therefore, your spielObjekt variable should look like this:

var spielObjekt = [{team1: "Teamname 1"},{team2: "Teamname 2"},{court: ""}];

Instead of using the push method, simply assign the spielObjekt variable to $scope.spielListe. This way, your <li> will be printed three times.

$scope.spielListe = [];
var spielObjekt = [{team1: "Teamname 1"},{team2: "Teamname 2"},{court: ""}];
$scope.spielListe = spielObjekt;

Answer №3

Scenario 1 : Only one object is passed in $scope.spielListe, causing ng-repeat to iterate only once.

Scenario 2 : If spielObjekt contains an array of objects, each object must be iterated and added to the $scope.spielListe array.

Live Example :

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

myApp.controller('MyCtrl',function($scope) {
  $scope.spielListe = [];
  var spielObjekt = [
             {team1: "Teamname 1", team2: "Teamname 2", court: ""},
             {team3: "Teamname 3", team4: "Teamname 4", court: ""}
             ];
  
  for (var i in spielObjekt) {
    $scope.spielListe.push(spielObjekt[i]);
  }

  console.log($scope.spielListe);
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myApp" ng-controller="MyCtrl">
  <ul>
    <li ng-repeat="spiel in spielListe">Do something</li>
  </ul>
</div>

In the provided code snippet, $scope.spielListe consists of an array with 2 objects, functioning correctly.

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

Utilize unshift() method in JavaScript to insert form input into an array

I'm having trouble with adding elements to an array using a form and the unshift() method. The code snippet provided below isn't functioning as expected, and I need help understanding why. <form> <input id="input"></input> < ...

Vue alert: Issue encountered in watcher 'childItems' callback - 'TypeError: Unable to access property 'tag' as it is undefined'

I am currently in the process of developing the Store page for a web application. I am utilizing Axios to retrieve product data and display it in a Vue template. While the backend functionality is working correctly and the frontend is rendering successfull ...

Controller function failing to trigger

I'm new to asking questions, so if I've made a mistake, please let me know. I've searched for an answer here but couldn't find one. Any help would be greatly appreciated. I'm attempting to load a list of "Countries" using a contro ...

Ensure that the <TabPanel> content occupies the entire width and height of its parent container

Currently, I am working with React and material-ui. Specifically, I am utilizing an appbar with tabs and my goal is to have the content of each tab expand to full width and height when selected. If you'd like to see an example, check out this sandbox ...

What is the purpose of the c() function in JavaScript?

I recently stumbled upon some interesting JavaScript code in the source of a web page: function fsb329142055() { var b=new Array(57,50,102,50,52,99,50,53,52,56,102,98,102,98,101,102,101,49,53,61,101,99,110,57,111,78,109,54,114,111,56,48,102,38,1 ...

Is there a way to insert json data into a form input field using jQuery?

I am attempting to insert the JSON result into an input as the value. This is the code I am using: $.ajax({ type:"POST", url: '{% url "url_searchTour"%}', data: data1, success: function(jsonAjaxResult){ console.log(J ...

Javascript on-page scroll positioning

My current dilemma involves finding a solution to optimize in-page scrolling for mobile users. I have a sticky header on the page, which causes #section1 to place the scroll position behind the sticky header. Is there a way to adjust the scroll position b ...

The webpage is unreachable on localhost after attempting to write to a file using node.js

I'm currently attempting to update a file using Node.js. I have a form that contains checkboxes, and upon form submission, the server should update the file based on which checkboxes are selected: a, b, or c. The JSON file structure is as follows: { ...

Troubleshooting Issue with Ionic's UI Router

Recently, I created a basic Ionic app to gain a better understanding of UI router functionality. To my surprise, when I ran the app, nothing appeared on the screen. Additionally, the developer tools in Google Chrome did not show any errors or information. ...

Configuring Chart.js in Laravel to Initialize with Value of Zero

I'm struggling to set my Chart.js chart to zero in my Laravel project. Could someone please help me with this? $chartjs = app()->chartjs ->name('lineChartTest') ->type('bar') ->size(['width' => ...

Recording Audio Using ReactJS

I am exploring ways to record audio using ReactJS and save it on my Node server. Initially, I attempted to utilize the "react-audio-recorder" module but encountered issues when attempting to record multiple audios consecutively. Additionally, I experiment ...

The default setting for my bootstrap modal is displayed, not hidden

Is there a way to make my bootstrap model hidden by default and only visible when I click on a link? I'm new to web development and would appreciate any help. tst.html <!DOCTYPE html> <html lang="english"> <head> < ...

What is the process for integrating an image from a byte array alongside additional content in CodeIgniter?

I am currently facing an issue with displaying a user's profile view using an image from a byte array. While I have successfully rendered the image, I am struggling to integrate it with other profile content due to the header('Content-Type: image ...

I am utilizing jQuery's AJAX function with a datatype of HTML to extract a specific portion of the incoming data

This is the JavaScript function I am working with: function getCountryRegions() { var postData = "id="+$("#selectedCountryId").val(); $.ajax({ url:"/region", data: postData, dataType:"html", type:"POST", ...

The plugin 'vue' specified in the 'package.json' file could not be loaded successfully

There seems to be an issue with loading the 'vue' plugin declared in 'package.json': The package subpath './lib/rules/array-bracket-spacing' is not defined by the "exports" in C:\Users\<my_username>\Folder ...

Using both Typescript and Javascript, half of the Angular2 application is built

My current project is a large JavaScript application with the majority of code written in vanilla JavaScript for a specific platform at my workplace. I am looking to convert this into a web application that can be accessed through a browser. I believe thi ...

Explanation for the strange floating math in JavaScript - Understanding the IEEE 754 standard for laymen

When it comes to JavaScript and working with floating point numbers, I always feel a bit lost. Dealing with decimals makes me nervous because I'm never quite sure what's happening behind the scenes. If only I understood how the IEEE 754 standard ...

What's the quickest method for duplicating an array?

What is the quickest method for duplicating an array? I wanted to create a game, but I found that Array.filter was performing too slowly, so I developed a new function: Array.prototype.removeIf = function(condition: Function): any[] { var copy: any[] ...

Troubleshooting issue: Dexie.js query using .equals not functioning properly in conjunction with localStorage

I am attempting to retrieve a value from indexedDB using Dexie.js, but it seems that the value stored in localStorage is not being recognized. I have tried various methods including async/await, promises, placing the localStorage call in created, mounted, ...

Unused function in Vue error compilation

I am facing an issue with the compiler indicating that the function 'show' is defined but never used. The function show is being used in HTML like this: <b-card> <div id="draw-image-test"> <canvas id="can ...