Instructions on how to use an API call to update database information in an Angular application

When making an API call to retrieve a list of data, I utilize ng-repeat to iterate through the items (which consists of over 100 entries).

To fetch the data list, I make an API call in the App Controller of my AngularJS app like this:

 var path = serverUrl + 'api/getAllMails';
    $http.get(path).then(function (result) {
      $scope.mails=result
    })

To display the mails in an HTML file, I use a table structure as shown below:

<table>
    <tr class="header">
        <th class="center">Id</th>
        <th class="center">Mode of Payment</th>
        <th class="center">Payment Collected</th>
        <th class="center">Status</th>
    </tr>
    <tr ng-repeat="mail in mails">
        <td>{{mail.id}}</td>
        <td>{{mail.paymentType}}</td>
        <td>Rs. {{mail.cost}}
            <input type="text" ng-model="mail.cost">
            <button ng-click="updateCost=(mail.id, mail.cost)">Update Cost</button>
        </td>
        <td>{{mail.status}}
            <input type="text" ng-model="mail.status">
            <button ng-click="updateStatus(mail.id, mail.status)">Update Status</button>
        </td>
    </tr>
</table>

In the initial iterations, the cost is set to "100" and the status is set to "pending". If I need to update this row by changing the cost to "1000" and the status to "Delivered", how can I achieve this?

In the AngularJS App controller, I have defined two methods for updating data via APIs and modifying the database records to provide the updated list of mails.

$scope.updateStatus = function(mailId, mailStatus) {
    var path = serverUrl + 'api/updateStatus';
    $http.get(path, {
        params: {
            mailId: mailId,
            mailStatus: mailStatus
        }
    }).then(function(result) {
        $scope.mails = result
    })
}

$scope.updateCost = function(mailId, mailCost) {
    var path = serverUrl + 'api/updateStatus';
    $http.get(path, {
        params: {
            mailId: mailId,
            mailCost: mailCost
        }
    }).then(function(result) {
        $scope.mails = result
    })
}

Although the code functions properly, there is an issue with page loading time. How can I optimize the loading performance or is there a more efficient approach to achieving the same functionality?

Any suggestions or assistance would be greatly appreciated. Thank you.

Answer №1

Instead of replacing the entire dataset unnecessarily, it is more efficient to update only the specific row that has changed. Make sure your updateStatus function returns the object you modified and then update that particular item in $scope.mails

For example

$scope.updateCost = function(mailId, mailCost) {
    var path = serverUrl + 'api/updateStatus';
    $http.get(path, {
        params: {
            mailId: mailId,
            mailStatus: mailCost
        }
    }).then(function(result) {
        // result represents the modified item
        for (var i = $scope.mails.length - 1; i >= 0; i--) {
            if($scope.mails[i].id === mailId) {
                $scope.mails[i] = result;
                return;
            }
        };
    })
}

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

unable to inject $modal within the Angular module

I am developing an AngularJS application and I need to include a modal popup as part of it. I was able to get it working in plunker: http://plnkr.co/edit/FtH8hkuaEj5A2zhMJdnE?p=preview. However, when I try to integrate it into the actual app, I encounter a ...

unable to retrieve response.entity message within $http error handling function

I am new to using AngularJS and have developed a JAX-RS RESTful API application that uses filters to accept or reject basic authentication calls. I tested my application in Postman and it works fine. I receive an error message if I don't pass the corr ...

What is the best way to utilize React Material UI's transition components for animating the addition of an item to a list?

I have a particular class in mind. class ClassExample extends React.Component { constructor(props) { super(props); this.state = { elements: [] }; this.add = this.add.bind(this); this.clear = this.clear.bind(this); } add() ...

What could be causing the error with firebase Sign In in next.js?

I set up a sign in page to enter email and password for Firebase authentication. The sign up process works fine, but I'm encountering an issue with the sign in functionality. 'use client' import { useState } from 'react'; import { ...

Activate SVG graphics upon entering the window (scroll)

Can anyone assist me with a challenging issue? I have numerous SVG graphics on certain pages of my website that start playing when the page loads. However, since many of them are located below the fold, I would like them to only begin playing (and play onc ...

Ways to conceal the ng-click attribute within the document object model

I am diving into the world of AngularJS and trying to expand my knowledge. I've encountered a roadblock where I need to trigger a click event without using ng-click="myFunction()". Ideally, I want to keep the function being called hidden. <input t ...

Can the z-index property be applied to the cursor?

Is it possible to control the z-index of the cursor using CSS or Javascript? It seems unlikely, but it would be interesting if it were possible. Imagine having buttons on a webpage and wanting to overlay a semi-transparent image on top of them for a cool ...

changing the value of a text input based on the selected option in a dropdown using ajax

I attempted to update the text input value with data from the database after selecting an option from the dropdown list. However, I encountered an issue where the data is not populating the text input field. <?php //Including the database configuration ...

Why is the JSP command <%=%> getting overlooked within a Javascript statement located inside a taglib tag declaration?

Allow me to provide an example to make this concept easier to understand! The jsp file... <%@ taglib prefix ="jam" uri= "http://jam.tld" %> <%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="ISO-8859-1"%> <% ...

Determing the dimensions of the browser's scroll bar

I have come across a query regarding the calculation of browser scrollbar sizes. However, my focus is on understanding how the solution in the npm package called scrollbar-wdith actually works. Can someone provide an explanation for this? To give some con ...

How is it possible that this event listener is able to capture an event that was already sent before it was

I am facing an issue with my Vue JS code. When I click on the account <a> tag, it triggers the toggle method. The toggle method adds an event listener to the document. However, as soon as the toggle method is executed, the event listener fires and ...

jquery autocompleter failing to function within ajax tabs

Currently working with the Symfony framework, my project includes 3 tabs: home, profile, and interaction. To enhance user experience, I have implemented ajax tabs functionality. Specifically in the interaction tab, I have integrated a jQuery autocomplete f ...

Simple steps for importing JS files in a web application

Upon examining the code snippet below: const express = require('express'); const app = express(); const http = require('http').Server(app); const io = require('socket.io')(http); const cors = require('cors'); app.u ...

Scope change causing angular array item to not update properly

After spending several hours on this issue, researching various Stack Overflow posts and blogs, I am still struggling to get my model to update correctly. Specifically, I am attempting to update an item within an array (using ng-repeat). In the example bel ...

Establishing a global variable in Cypress through a function

My current workflow involves the following steps: 1) Extracting a field value from one page: var myID; cy.get('#MYID'). then(($txt) => { myID= $txt.text(); }) .should('not.equal', null); 2) Mo ...

Adjust the output number in a JavaScript BMI calculator to the nearest whole number when using the

Hey there, I'm currently working on a beginner project and could use some assistance. My project involves creating a basic BMI calculator using metric units, but I seem to be encountering issues with rounding numbers. Here is a snippet of my code: var ...

Issue with Vuejs where changes are made to the parent array, but the child component does not detect those

I'm facing an issue where my parent component has the following code: {{ fencing }} <FencingTable v-if="fencing.length > 0" :fencing="fencing" :facility="facility" /> get fencing() { return this.$sto ...

Removing exclamation points from the routing of a state URL is a key aspect of mastering full stack development

Is there a way to remove exclamation marks from the url in state routing using mean.io? Currently, my url looks like http://localhost:3000/#!/auth/register I just want to get rid of the "!" marks after the "#" symbol. Is it possible? Here is the content ...

What is the best way to show inline icons within menu items?

Issue Upon selecting an option from the menu, I encounter a problem where the icon (represented by a question mark inside a speech bubble) appears on a different line than the text ("Question"). Fig. 1. Display of menu after selection with the icon and t ...

Avoid reloading the page when submitting a form using @using Html.BeginForm in ASP.NET MVC

I have a webpage featuring a model that needs to be sent to the controller along with additional files that are not part of the model. I have been able to successfully submit everything, but since this is being done in a partial view, I would like to send ...