Ng-repeat seems to be having trouble showing the JSON data

Thank you in advance for any assistance. I have a factory in my application that utilizes a post method to retrieve data from a C# function. Despite successfully receiving the data and logging it to the console, I am facing difficulties in properly displaying it using ng-repeat.

I've experimented with various nesting structures for ng-repeats without success. I suspect there might be an issue with how I passed the data or possibly a scope problem. I even tried passing data.d to hangar.ships instead of just data. As I'm still learning Angular, any guidance to steer me in the right direction would be greatly appreciated.

App Code:

var app = angular.module('shipSelection', ['ngRoute', 'ngResource']);

app.controller('ShipController', function ($scope, ShipService) {
    var hangar = this;
    hangar.ships = [];

    var handleSuccess = function (data, status) {
        hangar.ships = data;
        console.log(hangar.ships);
    };

    ShipService.getShips().success(handleSuccess); 
});

app.factory('ShipService', function ($http) {
    return {
        getShips: function () {
            return $http({
                url: '/ceresdynamics/loadout.aspx/getships',
                method: "post",
                data: {},
                headers: { 'content-type': 'application/json' }
            });
        }
    };
});

Markup:

<div class ="col-lg-12" ng-controller="ShipController as hangar" > 
    <div class =" row">
        <div class="col-lg-4" ><input ng-model="query" type="text"placeholder="Filter by" autofocus> </div>
    </div><br />
        <div class="row"> 
            <div ng-repeat="ship in hangar.ships | filter:query | orderBy:'name'">              
             <div class="col-lg-4">    
                <div class="panel panel-default">        
                    <div>
                        <ul class="list-group">
                            <li class="list-group-item" >
                               <p><strong>ID:</strong> {{ ship.ShipID }} <strong>NAME:</strong> {{ ship.Name }}</p>
                                           <img ng-src="{{ship.ImageFileName}}" width="100%" />      
                            </li>
                        </ul>
                    </div>                                              
                </div><!--panel-->
              </div> <!--ng-repeat-->
            </div>  
       </div> 
  </div> <!--ng-controller--> 

JSON returned from the post (From the console.log(hangar.ships):

Object
d: "[{"ShipID":"RDJ4312","Name":"Relentless","ImageFileName":"Ship2.png"},{"ShipID":"ZLH7754","Name":"Hercules","ImageFileName":"Ship3.png"},{"ShipID":"FER9423","Name":"Illiad","ImageFileName":"Ship4.png"}]"
__proto__: Object

Answer №1

According to the new update in AngularJS version 1.2, arrays are no longer automatically unwrapped from a Promise (refer to migration notes for more information). While I have observed it still working with Objects, it is advisable not to rely on this behavior based on the official documentation.

To address this issue, you can refer to this helpful answer: Angular.js not displaying array of objects retrieved from $http.get

Have you tried adding JSON.parse(data); to see if it resolves the problem?

If successful, consider incorporating additional checks and possibly transferring that logic to the service or utilizing $resource as suggested in another response.

For further details, please visit: https://github.com/angular/angular.js/commit/fa6e411da26824a5bae55f37ce7dbb859653276d

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

Material UI Grid's layout does not support placing a select element within a row

As a newcomer in the world of full stack development, I am delving into coding projects to enhance my understanding of frontend technologies like React JS and Material UI. My latest endeavor involves creating a page that displays posts from the backend in ...

Leveraging JavaScript to identify web browsers

I am looking to implement a feature on my website where if the visitor is using Internet Explorer 8.0 or an earlier version, they will receive an alert prompting them to upgrade their browser before proceeding. For users with other browsers, the page will ...

Transforming JSON date object into an Android Java date object

I have come across this JSON data, and it contains a news_date object in a strange format. "news_date":"\/Date(1452412800000)\/" Here is the full JSON: [{"ID":1,"title":"Add News RSS and WordPress feeds into the ultimate Android News app","det ...

Exploring nested documents in mongoDB with mongoose

As a novice full stack web developer, my current project involves creating a movie rating website. To achieve this, I have set up a user schema using mongoose with a ratings subdocument. Here is an example of the schema: const ratingSchema = new mongoose. ...

Maintaining a live Angular website

I'm currently in the process of developing a website for a family friend using Angular as a Single Page Application with three main 'pages'. After completion, my plan is to package it into an html, css, and js file. I've also secured th ...

Error: Custom Service is behaving unpredictably

My latest project involves creating a customized service. While the service function is returning data as expected, I encounter an issue when calling it in the controller - it returns 'undefined'. Service: var toDoListServices = angular.module( ...

Utilizing Jackson JsonSerializer with the @ResponseBody annotation in Spring for an enum interface

Similar inquiries Spring @ResponseBody Jackson JsonSerializer with JodaTime Usage of @JsonSerialize and JsonSerializer The Issue at Hand In my code, there is an enum defined as follows: @JsonSerialize(using = JSONI18NSerializer.class) public enum Stat ...

My JavaScript code is functioning properly in jsfiddle, but when I try to run it on my own website, I encounter

Encountered an error message stating "Uncaught typeError: cannot call method 'hover' of null" following the line $('#nav li a').hover(function(){ in my JavaScript code. Check out the code on my site here: http://pastebin.com/GjZBEu3s Y ...

JavaScript Thumbnail Slider Builder

I've been working hard on developing a custom JavaScript thumbnail slider that uses data-src. Everything seems to be in order, except the next and previous buttons are not functioning properly. Any assistance would be greatly appreciated. Here's ...

Navigating with Angular 2: Expressing HTML 5 Routing Challenges

I'm currently working on a simple web application using Express 4 and Angular 2. The only Angular 2 specific aspect in this project is the utilization of its HTML5 router. Let me walk you through how the routing works in this app: There are two prim ...

Error: The PHP contact form is displaying field names instead of the actual values being entered

I am completely new to this and would appreciate some guidance. I have set up a contact form on a website, but I seem to be encountering some errors. Here is the email content I receive from the contact form: <p>$usersname has contacted you from you ...

What is the best approach to achieve the old THREE.SpriteAlignment effect in the latest version of three.js?

After adapting an old three.js code for my application that includes a 3D function with axes grids, I encountered an issue when trying to update it to the latest revision, r74: https://jsfiddle.net/cjfwg2c4/ Without THREE.SpriteAlignment.topLeft, sprites ...

Is there a way for me to keep track of mongodb in real-time?

Is there a way to showcase real-time MongoDB monitoring statistics on a website without the availability of a real-time REST API or JSON output from mongostat? I considered redirecting stdout to a JSON file using a tool, but I am open to other suggestions ...

Global Path in Helmet Content Security Policy is not functioning as expected

I recently implemented Helmet to establish content security policies for my web application using Express in the backend. The specific policies are as follows: const express = require("express"); const app = express(); const helmet = require('helmet&a ...

Updating the component following an API request in ReactJS

I'm currently working on a component that allows users to search for friends by entering their email address. The interface consists of an input form where users can submit the email and I want to display the friend's information below the form a ...

What is the best method for checking for JavaScript errors when using Selenium WebDriver in conjunction with NodeJS?

When it comes to coding in JavaScript, not Java, my focus is on running a specific website like foo.com. I typically set it up as follows: var webdriver = require("selenium-webdriver"); By = webdriver.By, until = webdriver.until; var chrome = req ...

Using the Inline If-Else in AngularJS

<div class="alcohol"> <img src="~/img/Interaction/alcohol.png" title="Alcohol" /> <span>{{product.interaction}}</span> </div> If the value of {{product.interaction}} is 'CAUTION', the color of the sp ...

What could be causing the jQuery news ticker to malfunction on my site?

I recently made some changes to my main page by embedding HTML and adding the following code/script: <ul class="newsticker"> <li>Etiam imperdiet volutpat libero eu tristique.</li> <li>Curabitur porttitor ante eget hendrerit ...

The model name should not be overridden if it is already being used in different fields

I have a model that I am binding on two sides. The first side is inside an html p tag, and the second side is a textarea. When I make changes to the textarea, the content inside the p tag also changes. How can I ensure that only the content in the textar ...

Ways to halt a message callback?

Looking at some lines of code from a canvas sprite animation on GitHub, I am curious about how to stop the animations once the sprite has finished. window.requestAnimFrame = (function(callback) { // Function for handling animation frames return window.r ...