"Problem with AngularJS: Unable to display data fetched from resource using ng-repeat

I am currently working on an AngularJS application that retrieves data from a RESTful API using $resource. However, I have encountered an issue where the view is not updating with the data once it is received and assigned to my $scope.

As a beginner in AngularJS, there might be an error in my code that I am overlooking!

Below is my service implementation:

(function () {
    'use strict';

    var taxYearApp = angular.module('taxYearApp');

    taxYearApp.factory('costService', ['$resource', 
        function ($resource) {
            var theUrl = 'http://localhost/taxcalculator/api/CostApi/';
            var CostResource = $resource(theUrl + ':taxYearID', { taxYearID: 'taxYearID' }, { 'update': { method: 'PUT' } });
            return {
                getCosts: function (taxYearID) {
                    return CostResource.query({ taxYearID: taxYearID });
                }
            };
        }
    ]);
})();

This is how my controller is set up:

(function () {
    "use strict";

    var taxYearApp = angular.module('taxYearApp');

    taxYearApp.controller('costController', ['$scope', 'costService',
            function ($scope, costService) {
                $scope.Costs = [];
                var taxYearID = 1;
                var promise = costService.getCosts(taxYearID);
                promise.$promise.then(function () {
                    $scope.Costs = [promise];
                });
            }]);
})();

I have tried different approaches but none seem to solve the issue. Initially, I had

$scope.Costs = costService.getCosts(taxYearID);
.

Though I can see that $scope.Costs does contain the desired data array, the view is not being updated accordingly.

Here is the snippet of my view:

<div ng-controller='costController'>
    <div ng-repeat="Resource in Costs">
        <form name='item_{{$index}}_form' novalidate>
            <table>
                <tr>
                    <td><h3>{{Resource.CostType}}</h3></td>
                    <td><input type="number" ng-model="Resource.CostAmount" required /></td>
                </tr>
            </table>
        </form>
    </div>
</div>

The object has been renamed to 'Resource' based on the JSON format returned by the promise.

If I manually request the webAPI, this is the JSON response I receive:

[
    {
        "CostID": 1,
        "CostTitle": "Wage",
        "GrossAmount": 10001,
        "IsReadOnly": false
    },
    {
        "CostID": 2,
        "CostTitle": "Total Expenses",
        "GrossAmount": 3000,
        "IsReadOnly": false
    }
]

Any advice on what could be causing the issue or how to refresh the $scope with asynchronous data would be greatly appreciated.

Answer №1

To properly handle the data returned by a promise in AngularJS, make sure to assign $scope.Costs with the data inside the .then() function.

taxYearApp.controller('costController', ['$scope', 'costService',
        function ($scope, costService) {
            ...
            promise.$promise.then(function (data) {
                $scope.Costs = data;
            });
        }]);

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

What sets Fetch Promise apart in terms of delivery success?

Struggling with using strapi in my project, as the fetch function returns a promise instead of JSON data This is my code : const [products, setProducts] = useState([]); useEffect(() => { (async () => { try { l ...

Nesting placeholders is not permitted in i18n

I am attempting to implement Interpolation with Vue3 and vue-i18n version 9.3. However, when I try to pass arguments, I encounter the following error: Message compilation error: Not allowed nest placeholder 1 | Showing {{from}} to {{to}} of {{total}} ent ...

Using Vue.js to dynamically append varying inputs upon user interaction

When I select an option, I want to display different types of inputs based on the selected option. For Example: Select input -> show input fields Select textarea -> show text areas Select boolean -> show radio buttons The Code This is where ...

What is the process of transforming one JSON schema into another?

I am facing a task that requires mapping an input JSON file to a specific output JSON schema, but I'm unsure about the best approach. Should I convert from JSON to Java object, transform it, and then convert it back to JSON, or is there another way to ...

Is there a way to utilize Json.NET to convert a dynamic list of objects with varying names into a List?

Here is a sample JSON format that I am receiving from an external API: "data": { "category_2": { "info": { "detail": 1, "description": "Category 2" } }, "category_7": { "info": { "detail": 3, "description": "Categ ...

The JSON file is populated with just a single object when using a for loop

I am attempting to loop through a JSON file and extract specific key values to create a new JSON file: def get_rubrik_failed_archives_main(): with open("get_failed_archives.json") as json_file: json_data = json.load(json_file) for ...

What is the reason behind the browser crashing when a scrollbar pseudo-class is dynamically added to an iframe?

1. Insert a new iframe into your HTML: <iframe id="iframe-box" onload=onloadcss(this) src="..." style="width: 100%; border: medium none; "></iframe> 2. Incorporate the following JavaScript code into your HTML file ...

What is the best way to convert an array of data into a dataset format in React Native?

Within my specific use case, I am seeking to reform the array structure prior to loading it into a line chart. In this context, the props received are as follows: const data = [26.727, 26.952, 12.132, 25.933, 12.151, 28.492, 12.134, 26.191] The objective ...

What could be causing this template to malfunction?

Every time I try to start my Express server and access the page, I encounter an error. Can anyone pinpoint what might be wrong with the syntax? The "startzeit" property is a Date() Object. <tbody> <% for (let seminar in seminare){ %> ...

express-locale: locales property not functioning as intended

I've been experimenting with using express-locale (v1.0.5) as middleware in my express app to identify the locale based on the browser request. My goal is to compare the identified locale with a list of 'allowed' locales and use a default i ...

ASP.NET can have issues with the functionality of jQuery AJAX

I'm currently working on an asp.net webform project and I'm looking to implement jQuery ajax functionality. Below is the code snippet I have so far: <asp:Button ID="btn_comment" runat="server" CssClass="contact_btn pull-right" Text="send" OnC ...

Ways to interpret nested Json with scala?

Currently, I am utilizing Scala to parse JSON data with the given structure- "commands":{ "myinfo": [ { "utilization": { "sizeBytes": 998848331776, "usedBytes": 408722341888, "freeBytes": 590125989888 ...

Trigger the activation of an input field upon clicking an image labeled "edit"

I am currently developing a website where administrators have access to a dashboard page that displays a list of users. I am looking to implement a feature that allows admins to change the roles of other users directly from the same table row. Below is th ...

How can I use JavaScript fetch to retrieve data from a JSON file based on a specific value?

I am looking to extract specific values from a JSON array based on the ID of elements in HTML. How can I achieve this? [ { "product": "gill", "link": "x.com", "thumbnail": "gill.jpg ...

What is the best way to connect a fresh post to a different URL in ReactJS and Redux?

Currently, I am working with Redux and ReactJS to develop a discussion platform. One of the key features I am trying to implement is where users can input the title and content of their post, which will then be submitted to create a new post. After submit ...

How to effectively manage multiple stylesheet links in React Native Expo development

Hello, my name is Antika. I recently embarked on a coding journey and have been focusing on learning HTML/CSS/JS along with the basics of React. As a beginner developer, my current project involves creating a Study planner app for myself using React Native ...

Tips on adding style to your jQuery autocomplete dropdown

I am currently utilizing jQuery autocomplete functionality. I have configured it to communicate with a service and retrieve records: <script src="https://code.jquery.com/jquery-1.12.4.js"></script> <script src="https://code.jquery.com/ui/1 ...

Dynamically create a button using jQuery and JSON based on specific conditions (either true or false)

Is there a way to generate buttons with specified parameters only if a condition is true? Currently, the buttons are generated without checking conditions. Any help with the correct syntax would be appreciated. Sample JSON code: { "Caption": "Module ...

What is the correct method to choose an element in jQuery based on the function's id parameter

I'm having trouble deleting an item in my to-do list app. deleteToDoItem: function(id) { $(id).remove(); console.log(id); }, Here is the function that calls deleteToDoItem: function deleteItem(event) { var itemID, splitID, t ...

What could be the reason behind the varying outcomes browsers provide for the JavaScript expression new Date(-105998400000)?

When I use ASP.NET MVC 3 with the default Json serializer, I notice that dates from my JsonResults come back in the format /Date(-105998400000)/. To handle this, I extract the number and create a new Date object with this value. However, I am experiencing ...