AngularJS's $resource module returns an empty array as a response

I am trying to display a table with items from JSON data. I have created a Service that returns the JSON data. In my controller, I am querying the Service to receive an array of data. It's a little confusing because I am putting the response in a new JavaScript variable and then placing that JS variable in a scope variable. I am using the scope variable in the ngRepeat directive in my HTML file to display the data in the table, but it is not showing up as expected.

Service:

myApp.factory('MyService', function ($resource) {
    return $resource('data/mydata.json');
});

Controller:

var MyData = MyService.query(function () {
        $log.info('[Result:]', MyData); // console shows the expected data
    });

$scope.datas = MyData;
$log.info('Result2:', $scope.datas); // console shows an empty array

View:

<tr ng-repeat="item in filteredData = (datas | filter:search)>
    <td>{{ item.id }}</td>
    <td>{{ item.name }}</td>
</tr>

Normally, the data should be contained in the variable MyData, right?

EDIT: Now, I am facing a new issue where my list is not getting sorted. I am using the orderBy Filter from the AngularJS documentation website.

Answer №1

Your

MyService.query....

is an asynchronous call. The JavaScript does not wait for its response and executes the next line, which is

$scope.datas = MyData;

This results in an empty array being returned.

To fix this issue, update your code to:

var MyData = MyService.query(function () {
    $log.info('[Result:]', MyData); // Console will show the expected data
    $scope.datas = MyData;
    $log.info('Result2:', $scope.datas);
});

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

Identifying Hashtags with Javascript

I am trying to identify hashtags (#example) in a string using javascript and convert them to <a href='#/tags/example'>example</a> Currently, I have this code: var text = '#hello This is an #example of some text'; text.r ...

What is the method to implement timeago.js?

I've recently embarked on my journey to learn JavaScript, and it has only been two weeks since I started. As a beginner, I'm encountering some difficulties with implementing timeago from . The specific line of instruction that's giving me tr ...

Ways to prioritize HTML5/CSS3 navigation menu above the content

I am attempting to position my navigation menu on top of the content. Despite using z-index and overflow = visible, the desired effect is not achieved. I want to avoid setting the position relative as it will push the content downwards. Simply put, I want ...

Convert a JSON string with high-precision floating point numbers into a format that can be easily manipulated and retrieved

Python does not come with built-in support for arbitrary-precision floating-point numbers. Here is an example: >>> float(4.4257052820783003) 4.4257052820783 Regardless of the method used, Python cannot handle floats with arbitrary precision. Ima ...

The Node/Express Rest API appears to keep directing requests to the same controller function, despite the mappings being correctly

Currently, I am in the process of developing a node/express REST API. When making requests to the following endpoints: http://localhost:5000/api/news and http://localhost:5000/api/news/?id=c5f69d56be40e3b56e55d80 I noticed that both URLs trigger the same ...

Node-express can seamlessly switch between multiple databases dynamically

After extensive searching for a solution to my problem, I have come up empty-handed. If anyone has experience in similar situations, your help would be greatly appreciated. I have developed an application server in Node Express with MySQL as the database. ...

I am having trouble retrieving any data when using jQuery to post JSON data

I am struggling with some HTML and JavaScript code. Here is what I have: <html> <head> </head> <body> <script src="view/backoffice/assets/plugins/jquery/jquery-1.11.1.min.js" type="text/javascript"></sc ...

Updating token using an Ajax request in a PHP webpage

Currently, I am encountering an issue with my token system for requesting PHP pages via Ajax. The problem arises when attempting to make multiple Ajax requests from the same page as I am unable to refresh the token on the initial page. To elaborate furthe ...

Create a visual representation of a data structure using a JSON object in order to provide a comprehensive overview of the objects and their connections

Is there a way to create an SVG/PNG to illustrate the data structure of a JSON object? I remember generating images like the one in the attached file, but I can't seem to find the source anymore. I've searched on Google but couldn't find any ...

Trouble with toggling div visibility using jQuery and AJAX

I'm trying to display a specific div based on the result of an SQL query. The problem I'm facing is that I can't seem to toggle the divs asynchronously. Currently, the page needs to be reloaded for the div to reflect the changes. <?ph ...

Display various JavaScript function outputs in an HTML table for convenient tracking

Thanks to a helpful user on this platform, I was able to capture data from a JavaScript function and display it in an html table. However, I now have another query. How can I execute the function multiple times during page load and record the results in ...

Ways to detect the use of vue.js on a webpage without relying on vue-devtools

One way to determine if the page is utilizing Angular or AngularJS is by inspecting window.ng and window.angular. Is there a similar method to identify whether Vue is being used on the page directly from the console, without relying on vue-devtools? ...

Switching between different views in Angular UI-router by selecting one UI-view over another

On my page, I have set up 2 ui-views. The top view contains a form and some controls, while the bottom view initially displays a few tables but should change based on the user's actions in the top view. I chose to keep this initial setup within a sin ...

Changing the color of a specific span using Angular

I am working with a dynamic mat-table where columns are added and populated on the fly. The table headers are styled using divs and spans. My goal is to change the color of a header to black when clicked, but also un-toggle any previously selected header. ...

The Google Maps API allows all markers to be connected to a single infowindow

I've been grappling with this issue for some time now, but I just can't seem to find a solution! I'm retrieving data from a database in Laravel using Ajax and then attempting to display infowindows for each marker on Google Maps. The markers ...

What is the best way to make a CSS element move with Javascript?

Currently working on a JavaScript game where I am in need of a CSS object to replace the original JavaScript object. Specifically, I want my "sword" CSS object to move along with my player object when it is Unsheathead. All the examples I find only show wh ...

When Index.html is hosted via Express, the component fails to render

Following a tutorial has led me to the end and I've made changes to my App.js as shown below: import React, { Component } from "react"; import "./App.css"; class App extends Component { render() { return ( <div> <p>lm ...

Generating clickable markers that trigger an AlertDialog to appear in real-time

I am currently working on dynamically adding markers to a map, pulling data from JSON. The marker addition process is functioning correctly, as I can successfully add multiple markers in various locations. However, when I click on a marker, I want an alert ...

What is the best way to apply changes to every class in JavaScript?

Check out this HTML and CSS code sample! body{ font-family: Verdana, Geneva, sans-serif; } .box{ width: 140px; height: 140px; background-color: red; display: none; position:relative; margin-left: auto; margin-right: auto; } .bold{ font ...

What is the process for setting up an AngularJS file within the Struts.xml configuration?

Currently, I am in the process of creating a web application with Struts2. My aim is to retrieve data from a database and present it in .json format. However, I would like this information to be displayed on a JSP page in a tabular layout. When I execute t ...