Content not appearing in ng repeat loop

I'm facing a basic issue that I can't seem to solve - my code isn't working as expected:

<article id="desktop">
    <h3>Content: </h3>
    <ul>
        <li ng-repeat="x in storage">
            name: {{x.name}}
        </li>
    </ul>
</article>

Here's the AngularJS part of my code:

$scope.storage = [];    
...

$scope.showDesktop = function(){        
$http.get("/getDesktop").then(function(response){
    for(var i = 0; i<response.data.length; i++){
        $scope.storage.push({
            name: response.data[i]
        });
    }
    console.log($scope.storage);
    return;
});        
}

I suspect there might be a syntax error somewhere, even though I've checked the documentation and used the correct ng-repeat syntax.

Although the console.log shows the correct content, it still doesn't work as intended.

This is how my Spring controller is implemented:

    //Returns Desktop
@GetMapping("/getDesktop")
public ArrayList<String> getDesktop() throws Exception {
    ArrayList<String> itemNames = new ArrayList<>();

    if(kdxF.getLogged() && kdxF.getUser() != null) {
        itemNames = kdxF.showDesktop();
    }else {
        throw new Exception("Not logged in!");
    }   

    return itemNames;
}

Answer №1

To access the variable from the HTML, you must scope it.

var storage = []; //This is a private declaration and not accessible in HTML

Change it to $scope.storage = []; so that ng-repeat can access it.

Don't forget to update the variable in the API as well.

$http.get("/getDesktop").then(function(response){
    for(var i = 0; i<response.data.length; i++){
        $scope.storage.push({
            name: response.data[i]
        });
    }
    console.log($scope.storage);
    return;
}, function (err){
    //Log the error callback
    console.log(err);
});  

Updated: If there are issues with the ng-repeat tracking sequence, consider using

ng-repeat="x in storage track by $index"

Make sure to properly handle errors in the API calls.

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

Swapping DOM elements in an AngularJS application

I have two divs on a page, with only one visible at a time. Within the first div, there is a text input by default. Now, if the first div is hidden and the second div is shown, I would like to move the text input DOM into the second div while retaining t ...

Invalid preflight response (redirect) error

I am a beginner in utilizing Laravel and Lumen frameworks for my projects. Currently, I am working on my first project using Lumen and attempting to create an API call from Angular. Below is the Angular code snippet: app.controller('ListCtrl', ...

Executing directives in a sequential manner

I am facing a challenge with my HTML view that is filled with multiple Angular directives, each triggering numerous HTTP requests. This has resulted in high CPU usage due to the heavy load. Our proposed solution is to load one directive at a time, allowing ...

Incorporating EJS Template Body Parameters into AWS Lambda's Handler.js Using Serverless.yml

I have a scenario where I am trying to embed an EJS template named 'ui.ejs' into my handler.js file. The goal is to extract URL query parameters, then pass them to a function called 'ui.js' to retrieve data, which will then be displayed ...

Experiencing the AngularJS [$injector:modulerr] error message despite having flawless code

Despite having code that appears to be correct, I am consistently receiving an [$injector:modulerr] error when working with AngularJS. Check out the updated Fiddle here. I can't seem to figure out what the issue is. Could I be missing something obvi ...

What is the process for generating a fresh PSBT transaction using bitcoinjs-lib?

This is the code I've been working on import * as bitcoin from 'bitcoinjs-lib' const NETWORK = bitcoin.networks.regtest; const psbt = new bitcoin.Psbt({ network: NETWORK }); function p2shAddress(node: bitcoin.ECPairInterface): string { c ...

JavaScript can be used to call a web service directly from a content page

Is there a way to call an autocomplete webservice from JavaScript in a content page that is part of the same web app? I have found that when I include a master page, the autocomplete feature stops working. I haven't added a script manager to the maste ...

The significance of 'this' in an Angular controller

Forgive me for what may seem like a silly question, but I believe it will help clarify my understanding. Let's dive into JavaScript: var firstName = "Peter", lastName = "Ally"; function showFullName () { // The "this" inside this func ...

Having trouble with transferring information from JQuery to PHP

Currently, I'm working on transmitting data from jQuery to PHP. Here's an excerpt of what I've done: var jsonArray = JSON.stringify(dataArray); $.ajax({ type: "POST", url: "addcar_details.php", ...

Each $.each function varies based on the type of object it is iterating

I have encountered an issue with my $.each statement. When it is written like this: $.each($(".permissions"), function (index, element) { ... }).promise().done(function () {...}); everything works fine. However, when I change the $.each statement to: ...

Can you explain the purpose of the _app.js and _document.js files in Next.js? What is the significance of using an underscore (_) in Next.js?

After using npx create-next-app to create a next.js app, I noticed that there are 2 JavaScript files named app and document in the pages directory with an initial underscore. What is the purpose of this naming convention? The files appear like this: ▼ p ...

Exploring the fundamentals of JavaScript within the context of Express.JS

Can you please explain the distinction between these two blocks of code in JavaScript? app.get("/api/products/1", (req, res) => { const singleProduct = products.find((product) => { product.id === 1; }); res.json(singleProduct); }) ...

Accessing a property's value from a different property within a Class' initialization function

I encountered a challenge while trying to access the value returned in one method within a property of another method belonging to a different constructor. The specific error message I received was "TypeError: Cannot read property 'name' of undef ...

Adjusting MongoDB settings to permit cross-origin requests

I'm still new to using MongoDB, so I'm in the process of familiarizing myself with it. My current goal is to send a JSON object to MongoDB from the client side using the JavaScript code below. var addUserButton = document.getElementById('a ...

Navigating the division between presentational and container components in React/Redux

Here is a basic outline of my current setup: container.js: import Presentation from './Presentation'; import { connect } from 'react-redux'; export default connect( ({ someState}) => ({ ...someState }), (dispatch) => { ...

Restrict HTML Content in Json Result using PHP and Jquery

I'm currently working with a Controller that outputs JSON response and a JavaScript function that appends that response to the last tr in an HTML table. <pre> $reponse="<tr class=\"border_bottom\"><td>My Repo ...

What causes Chrome to automatically remove a script tag?

Hello everyone! Instead of utilizing jQuery, I have been creating a script tag and appending it to the head tag in order to retrieve JSONP data. However, after the JSONP callback function is executed, I have noticed that the script tag that I added to the ...

Obtaining documents through Mojolicious

Just a quick inquiry - I have successfully generated a .doc file using my mojolicious app with the help of the CPAN module MsOffice::Word::HTML::Writer. Now, the challenge I'm facing is figuring out how to make the browser initiate the download proces ...

What steps can I take to avoid keypress events causing issues with the browser's input functionality?

Utilizing Bootstrap's modal component, I have implemented an "Add User" dialog within my web application. In order to streamline the user experience and enable quick data entry, I am aiming for the escape and enter keys to close and submit the form re ...

Using angular.js to create ng-options with personalized values

After receiving a JSON object from an AJAX call, I have the following data: 0: Object id: "0-0-0" selected: "selected" text: "option name" value: 0 __proto__: Object 1: Object id: "12-0-0" selected: "" text: "4C 1.75 16v Tb ...