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

Using a Vue.js component in a Laravel Blade template can be achieved by first registering the component

I added a component registration in my app.js as shown below: Vue.component('navbar', require('./components/Navbar.vue')); Now I am looking to import that component into my blade.php file like so: <template> <nav class="navb ...

Using Vue.js watchers can sometimes cause an endless loop

I'm working on a unique aspect ratio calculator. How can I ensure my code doesn't get stuck in an endless loop when dealing with 4 variables that are dependent on each other? To address this, I implemented 4 watchers, each monitoring a specific ...

Improve page loading speed by removing JavaScript and CSS that block rendering of above-the-fold content, specifically focusing on Angular JS

Currently, I am working on improving the page speed of my MEAN stack application. My main challenge lies in eliminating render-blocking Javascript and CSS to enhance the loading time. Despite making significant progress, I have hit a roadblock with the con ...

The setInterval() function is not executing the IF Else statement correctly

I'm having an issue with accessing if else conditions. Currently, both the if block and else block are being called at the same time. I need help in making the if else block work properly. Here is a snippet of my code: const UserCard=(props)=>{ c ...

Angular UI grid: Arranging numbers in a straight line at the decimal point

I am interested in aligning decimal numbers in Angular UI Grid as shown below. 11.293 .89 233424 .34345 I have considered different approaches such as using a cell template with aligned divs or transparent 0s. Has anyone successfully imp ...

concealing the AngularJS scope

I'm facing an issue where I need to hide search results until the user starts typing in the search bar. The module I'm using is a DotNetNuke plugin, so I didn't create it myself. I believe I need to work with the scopes '.angrid-search& ...

What is the best way to navigate through a complex array in React that includes objects and nested arrays?

I have been working on a JavaScript array that includes subobjects with arrays nested in them. My goal is to iterate through the entire parent object using React. Although I attempted the following approach, unfortunately it did not yield the desired outco ...

An SQL query that functions flawlessly in STUDIO 3T, yet fails to execute in Express.js

I encountered a puzzling situation where a query that functions perfectly in STUDIO 3t fails to retrieve any data in express js. Below is the code comparison: STUDIO 3t Query: db.getCollection("tickets").find({ $and: [ {"TCKT_CRTE_DTTM" : { ...

Retrieving information from an openDatabase using AngularJS

Encountering an issue while trying to retrieve data from openDatabase and display it in a listview. Following advice from a thread, I added $scope.$apply(); after $scope.items = $data;, but this resulted in an error: [$rootScope:inprog] $apply already in p ...

The post request fails to send certain variables

I'm experiencing an issue with a form that has rows structured like this: <div class="row unit" onmouseover="this.style.background = '#eeeeee';" onmouseout="this.style.background = 'white';" onclick="if(event.srcElement.nodeNam ...

Stop the duplication of downloading JavaScript files

When it comes to my website, I have incorporated sliders that stream videos from Vimeo. Upon running a check on GTMetrix, I noticed an overwhelming number of http requests. Looking at the waterfall, I discovered numerous duplicate downloads of javascript, ...

Glitch with AngularJS Bootstrap date picker

Currently, I am working on integrating a datepicker into my PhoneGap application using Angular UI Bootstrap. <h4>Popup</h4> <div class="row"> <div class="col-md-6"> <p class="input-group"> <input type="text" cl ...

Remove an entry from a JSON document

Looking for help! I've got a JSON file with country capitals listed, and I want to figure out how to remove a specific key-value pair. Here's the JSON data I'm working with: { "data": [ { "Capital": "Berlin", "Countr ...

React does not accept objects as valid children

Currently, I am working on developing a stopwatch using reactive js. Here is the code snippet that I have been working on: <div id="root"></div> <script src="https://unpkg.com/library/react.development.js"></script> <script sr ...

Can an XSS attack occur on a style tag with inline styling?

For example: <!DOCTYPE html> <html lang="en"> <head> <title>Test for Potential XSS Attack</title> <style> div { background-color:blue; height:120px; ...

The React-Big-Calendar Drag and Drop feature in the month view consistently drags events from the leftmost column

I'm seeking assistance with a bug I've encountered while using the big-react-calendar. The issue arises when dragging an event, as it consistently moves to the leftmost column regardless of mouse position. However, shifting the event to a differe ...

Mobile site's call button functionality is malfunctioning

For the telephone number on my mobile site, I employed the <a href="tel:+1800229933">Call us free!</a> code. However, it seems to be malfunctioning on several devices. Any insight on this issue would be greatly appreciated. Thank you. ...

Can someone guide me on the process of adding a personalized emoji to my discord bot?

After creating my own discord bot, I'm ready to take the next step and add custom emojis. While tutorials have helped me understand how to use client.cache to type an emoji, I'm unsure of how to upload them and obtain their ID for use in my bot. ...

Tips for inserting data into a PHP modal using MySQL and Ajax

Here is the code snippet I've written: <div class="container"> <div class="row"> <div class="col-md-3"> <div id="accordion" role="tablist" aria-multiselectable="true"> <div class="card"> ...

Utilizing BEM Class Names in React

How can I utilize the Post component in a way that assigns unique classes to new and old posts following BEM recommendations? Assign a unique className to every element Avoid cascading dependencies like (.posts-new post or .posts-old post) Each component ...