Showing real-time results of adding or deleting an operation on a web page using AngularJS and Spring MVC

I have created an employee form that allows users to add, search for, and delete employee details. Within the controller, I have separate functions for these operations. After adding or deleting an employee, I want the result list to update dynamically (showing added employees but not deleted ones). How can I achieve this? Should I call the search function again after a successful delete operation, or is there another way to accomplish this? My technology stack includes Angular JS and Spring MVC.

This is the Controller Code for the Search:

$http.post('http://localhost:8080/services/employee/search/'+Systems+"", searchCriteria)
.then(function(response) {
   $scope.searchresponse= [];
   $scope.searchresponse = response.data.items;
   if (response.data && response.data.items.length != 0) {
        $scope.searchresponse = response.data.items.map(function (x) {
            x.selected = false;
            return x;
        });
        console.log($scope.searchresponse);
   } 
   else {
        $scope.showerror = true;
        $scope.ErrorMsg ="There is no record matching your criteria."
   }
});

This is the Search Response From API:

{
    "items": [{
       "employeeId": "ABC",
       "type": "D",
       "alive": "Yes"
    }, {
       "employeeId": "DEF",
       "type": "A",
       "alive": "Yes"
    }],
    "more": false
}  

This is the Controller call for Delete:

 var data1=["ABC", "NPK"];
$http.delete('http://localhost:8080/services/employee/delete/'+Systems+"", {data:{"idList":data1},headers: {'Content-Type': 'application/json'}} )
.then(function(response) {
console.log("testing");
// - here i would like to implement code to remove all the fields that belong to eomployee id ABC,NPK from result page  
        });

I am utilizing selectall/deselect all checkboxes to provide users with the option to remove multiple items.

Answer №1

Imagine you have an employee with properties like name and id, along with a specific http resource uri to identify that employee, for example:

http://yourservice/employees/123 

and a service to delete this employee.

When displaying the list of employees in your view, you might do it as follows:

<ul>
   <li ng-repeat="employee in employeeList track by employee.id">  
      {{employee.name}} <button ng-click="deleteEmployee(employee.id)">delete</button>
   </li>
</ul>

In your controller, the function triggered when the user clicks the delete button on an employee could look like this:

$scope.employeeList = [...];

$scope.deleteEmployee = function(employeeId) {
    let empUri = 'http://yourservice/employees/'+employeeId;
    $http.delete(empUri).then(function(response) {
       // Successful deletion, remove employee from the list 
       let empIndex = $scope.employeeList.findIndex(e => e.id === employeeId);
       $scope.employeeList.splice(empIndex, 1);
    }, function(responseError) {
       // Deletion error. Display an alert...
    });
}

The updated employee list should be reflected in the view.


UPDATE
To remove multiple employees from the search result, you can simply filter the list, for instance (based on your code):

var data1=["ABC", "NPK"];
$http.delete(/* delete service url and data */).then(function(response) {
    // Filter out employees from data1  
    let empList = $scope.searchresponse.filter(emp => {
        // Is emp not in data1?
        return !data1.some(remEmpId => remEmpId == emp.employeeId);
    });
    $scope.searchresponse = empList;
});

Answer №2

To eliminate data from the given List in the response, you can utilize Array.splice method.

for (let i = 0; i < $scope.employeeList.length; i++) {
  if ($scope.employeeList[i].employeeId == employeeId) {
    $scope.employeeList.splice(i, 1);
    break;
  }
}

Check out the live demonstration at this link

I trust this information is beneficial for your needs!

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

Creating dynamic components in Vue.js using VueJS and jQuery synergistically

New to Vue.js and in the process of building a Vue component inspired by this custom select menu. I want to include an ionicon with each list item. Typically, I can add the icon in Vue.js using: <component class="icon" :is="name-of-icon& ...

Receiving JSON output from nightwatch.js

Is it possible to execute a JSON object from an HTML ul list like this? {name: "Nick", surname:"Kyrgios", age: "22", city: "Sydney"}, {....}, {....} Here is the corresponding HTML code: <html> <ul> <li class="user"> <div class ...

Tips on combining $scope object values within AngularJS

I am extracting data from various SharePoint pages lists by utilizing a Factory. Within my code, I am determining the number of items with a "Completed" status in each list. I am attempting to store these values in an array, but it consistently returns ...

ERROR UnhandledTypeError: Unable to access attributes of null (attempting to retrieve 'pipe')

When I include "{ observe: 'response' }" in my request, why do I encounter an error (ERROR TypeError: Cannot read properties of undefined (reading 'pipe'))? This is to retrieve all headers. let answer = this.http.post<ResponseLog ...

jQuery functions seamlessly on Chrome, Firefox, and Internet Explorer, unfortunately it does not work on iPhone

The code functions properly on desktop browsers, but encounters issues on iPhone devices. I would greatly appreciate it if you could take a look and help me identify the problem. What do you think could be causing this discrepancy? <ol style="margin: ...

The text remains static and does not adjust its size when the screen is

I'm currently utilizing the text-only carousel feature found at this jsFiddle link. Below is the code I am using for resizing: window.addEventListener("resize", resetCarousel); function resetCarousel(){ setCarouselHeight('#carousel-text&apos ...

What could be causing me to have to click the button twice in order to view my dropdown list? Any suggestions on how to

I am facing an issue where I have to click twice on the "Action" button in order to see my dropdown list. How can I resolve this? Is there a way to fix it? $(document).ready(function() { $(".actionButton").click(function() { $dropdown = $("#cont ...

What causes the exception in JavaScript to be an empty object?

try { let temporary = null; temporary.split(','); } catch (error) { Logger().info('caught error: ', error, error.constructor); } output: caught error: {} undefined I attempted to use JSON.stringify and encountered the sa ...

Efficiently transferring property values

In my current code, I have functions that retrieve specific properties from an object within an array. Since each object in the array has multiple properties, I find myself using separate functions to extract different properties. This approach is not eff ...

The parsing of a date string in JavaScript is done with the timezone of

let userInputDate = "2019-05-26" // received from browser query e.g. "d=1&date=2019-05-26" let parsedDate = new Date(userInputDate) console.log(JSON.stringify(parsedDate)) output: #=> "2019-05-25T19:00:00.0000Z" Issue When the user's time ...

Querying enums using the "in" clause with Spring Data JPA and HQL

What is the best way to write an HQL query with an "in clause" using an enum list? Here is the reserved entity: @Enumerated(EnumType.STRING) private ReservationState state; Repository code snippet: @Query(value = "select rez from Reservation rez wh ...

How to resolve CORS issues in an AngularJS, Spring Boot, and Nginx setup

For the past few days, I've been struggling with an issue. I have a backend server set up using Spring-boot with Rest API. This server is being called from a frontend interface built with AngularJS and managed by Nginx. Everything is running locally ...

How can I use JavaScript to find a keyword on a webpage that is not located within an <a> tag or its href attribute?

I'm on a mission to locate a specific keyword within a webpage. Sounds simple, right? Well, here's the tricky part - I need to disregard any instances of this keyword that are nested within an <a> tag. For example: <p>Here is some s ...

Guide on changing the background color of a specific row with pagination

https://i.stack.imgur.com/Q4ggc.png Currently, I'm implementing pagination on an array and need to highlight the rows with a count of zero. The count variable in each row can be accessed using {{x.count}}. I want to customize the background color fo ...

When the tab on my website is clicked, the fontawesome icons elegantly transition into their designated positions

When my website loads, some of the fontawesome icons pop in after the animations finish. Specifically, two out of four icons used for visual representation of my skills (such as 'Sound Design' with a headphones picture) pop in when it gets to the ...

Attempting to craft a multi-filter feature using AngularJS that will allow for the precise filtering of JSON data based on both month and year identifiers

I have integrated AngularJS into the RoR framework and am working on creating a multi-filter for the "ng-repeat" function to filter JSON data based on "month_id" and "year_id". Here is the current code: JSON: [ { "date":"October 4, ...

Establishing a minimum date based on the date selected in the earlier datepicker

My webpage features two date pickers, one for startdate and the other for enddate. The current setup requires that the second datepicker remains inactive until a change is made to the first one. The datepicker for enddate is initially set with the startin ...

Reverse a filter within an ng-repeat loop - AngularJS

I have a question that I haven't found the answer to yet. Here is the issue I'm facing: The JSON data I am working with has this structure: [{ "batch_queue_name": "Batch One", "start_date": "12/01/2016 10:18 P.M.", "end_date": "12/03/2016 ...

Bizarre error in rendering angular template

Included in my index.html file is the following code: ...... <my-test-app></my-test-app> <script src="bower_components/angular/angular.js"></script> <script src="bower_components/angular-component-router/angular_1_router.js"> ...

jQuery uploadify encountered an error: Uncaught TypeError - It is unable to read the property 'queueData' as it is undefined

Once used seamlessly, but now facing a challenge: https://i.stack.imgur.com/YG7Xq.png All connections are aligned with the provided documentation $("#file_upload").uploadify({ 'method' : 'post', 'but ...