Updating a JSON data structure after removing an item using AngularJS

As a newcomer to AngularJS, I have created a Service using Java and integrated it into Angular to handle the deletion of Contact objects.

On my homepage in AngularJS, this is the code I have:

<!--RESULTS-->
<form>
<table class="table table-striped" ng-controller="HomeController">
  <tr>
    <th></th>
    <th>Last Name</th>
    <th>First Name</th>
    <th>Phone Number</th>
    <th>Email </th>
    <th></th>
  </tr>

  <tr ng-repeat="contact in allContacts | filter:search | orderBy:'lastName'">
    <td align="center"><img src="{{contact.picture}}" height="40" width="40"/></td>
    <td class="td_data">{{contact.lastName}}</td>
    <td class="td_data">{{contact.firstName}}</td>
    <td class="td_data">{{contact.phone_1+" "+contact.phone_2}}</td>
    <td class="td_data">{{contact.email}}</td>
    <td class="td_data"><button type="button" class="btn btn-danger" ng-controller="HomeController" ng-click="deleteContact(contact)"><i class="glyphicon glyphicon-trash"></i></button></td>
  </tr>
</table>

The controller code looks like this:

var module = angular.module('home.controllers', [])
.run(function($rootScope) {
$rootScope.is_hide_add_message = true;
$rootScope.alert_message = "";
})
module.controller('HomeController', function ($scope, $rootScope, $state, Contacts, $timeout) {
var allContacts = {};
        /** DELETE A CONTACTS*/
    $scope.deleteContact = function(contact){
        /** GET INDEX OF OBJECT TO DELETE */
        var index = $scope.allContacts.indexOf(contact);

        /** DELETE THE OBJECT SELECTED */
        Contacts.deleteContact(contact.id);
        /** DELETE THE OBJECT FROM THE JSON */
        $scope.allContacts.splice(index, 1);

        $rootScope.alert_message = "The contact has been successfully deleted.";

        /**DISPLAY THE MESSAGE*/
        $rootScope.is_hide_add_message = false;
        $timeout(function() {
            $rootScope.is_hide_add_message = true;
        }, 3000);
    };
}
);

After clicking on the delete button, the object is removed from the database but the <table> is not updated. The line

$scope.allContacts.splice(index, 1);
seems to be functioning correctly during debugging, yet the table does not refresh.

Answer №1

It seems that the issue lies in specifying ng-controller="HomeController" twice. You can remove one instance from the button.

Answer №2

Perhaps this can provide some assistance as I have included a demo code below. Take a look:

var app = angular.module('myApp', []);

app.controller('HomeController', function($scope) {
  var Contacts = [{
    "lastName": "ABC1",
    "firstName": "XYZ",
    "phone_1": "123456",
    "phone_2": "789456",
    "email": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="86e7e4e5defffcc6e1ebe7efeaa8e5e9eb">[email protected]</a>",
  }, {
    "lastName": "ABC2",
    "firstName": "XYZ",
    "phone_1": "123456",
    "phone_2": "789456",
    "email": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="39585b5a614043795e54585055175a5654">[email protected]</a>",
  }, {
    "lastName": "ABC3",
    "firstName": "XYZ",
    "phone_1": "123456",
    "phone_2": "789456",
    "email": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="c9a8abaa91b0b389aea4a8a0a5e7aaa6a4">[email protected]</a>",
  }, {
    "lastName": "ABC4",
    "firstName": "XYZ",
    "phone_1": "123456",
    "phone_2": "789456",
    "email": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="a3c2c1c0fbdad9e3c4cec2cacf8dc0ccce">[email protected]</a>",
  }, {
    "lastName": "ABC5",
    "firstName": "XYZ",
    "phone_1": "123456",
    "phone_2": "789456",
    "email": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="b0d1d2d3e8c9caf0d7ddd1d9dc9ed3dfdd">[email protected]</a>",
  }];
  $scope.allContacts = Contacts;
  /** REMOVE A CONTACT */
  $scope.deleteContact = function(contact) {
    /** GET INDEX OF OBJECT TO REMOVE */
    var index = $scope.allContacts.indexOf(contact);

    /** REMOVE THE OBJECT FROM THE JSON */
    $scope.allContacts.splice(index, 1);
  };
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<form ng-app="myApp">
  <table class="table table-striped" ng-controller="HomeController">
    <tr>

      <th>Last Name</th>
      <th>First Name</th>
      <th>Phone</th>
      <th>Email</th>
      <th>Action</th>
    </tr>
    {{allContacts}}
    <tr ng-repeat="contact in allContacts | filter:search | orderBy:'lastName'">
      <td class="td_data">{{contact.lastName}}</td>
      <td class="td_data">{{contact.firstName}}</td>
      <td class="td_data">{{contact.phone_1+" "+contact.phone_2}}</td>
      <td class="td_data">{{contact.email}}</td>
      <td class="td_data">
        <button type="button" class="btn btn-danger" ng-click="deleteContact(contact)">Delete<i class="glyphicon glyphicon-trash"></i>
        </button>
      </td>
    </tr>
  </table>

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

Sending Laravel 5.4 Controller Response to Blade Using Ajax (Fixing json_encode() Error with Object Parameter)

I am trying to send data from the controller to AJAX as an array, but I am encountering the following error: json_encode() expects parameter 2 to be integer, object given Below is my code snippet: function get_show(Request $request) { $i ...

Despite being used within useEffect with await, asynchronous function fails to wait for results

In my component, I am utilizing a cookie value to determine which component or div block to display. The functionality works correctly in the end, but there is a brief moment where it seems like the cookie value is not being checked yet. During this short ...

Adding images to your SVG using Bobril is a simple process that can add visual

I have been attempting to insert an image into an SVG using Bobril, but the following code is not functioning as expected: { tag: 'svg', children: { tag: 'image', attrs: { 'xlink:href': &ap ...

Trouble with submitting a form and showing a success message in AngularJS version 1.6.8

My query submission form consists of fields for name, email, and the actual query. The component includes a controller function with a submit function to handle form submission. To submit user input and display a success message upon submission, I utilize ...

Rearranging components in React does not automatically prompt a re-render of the page

I'm currently working on a project to display the update status of my Heroku apps. The issue I encountered was that the parent component (Herokus) was determining the order, but I wanted them sorted based on their update dates starting from the most r ...

methods for extracting data from nested JSON arrays in Android

Can anyone assist me in fetching the URL from the JSON array thumbnail_images? The URL I need is nested inside another array called medium_large. I have successfully retrieved the URL from the following JSON: "attachments": [ { "id": 367, "url": ...

There seems to be a problem with the external JavaScript file not functioning

After dragging and dropping the .js file into my ASP.NET project, I am facing an issue where it remains unresponsive, even though the code works fine when used inline. This problem is occurring while using VS 2017. Here is a snippet of my code: <scrip ...

Enhance the overall appearance of select elements across all components using Material UI's

I'm attempting to change the border color of my outlined select elements using the code below, but it's not working as expected. It seems that the border style is being inherited from the fieldset element. I've experimented with using MuiOut ...

Unable to find '/images/img-2.jpg' in the directory 'E:React eact-demosrc'

My code is giving me trouble when trying to add an image background-image: url('/images/img-2.jpg'); An error occurred during compilation. ./src/App.css (./node_modules/css-loader/dist/cjs.js??ref--5-oneOf-4-1!./node_modules/postcss-loader/src?? ...

Mastering the art of resolving a dynamic collection of promises with '$.all'

Imagine having 3 promises and passing them to $q.all. This results in a new promise that resolves when the 3 promises are resolved. But what if I realize before the 3 promises resolve that I also want a 4th promise to be resolved? Can this be achieved? I ...

Is there a potential race condition in React when switching between lists?

I'm currently working on setting up a queue system where users can move items between different lists, such as from "available" to "with client". The queue's state is managed in the root React component like this: this.state = { queue: { a ...

Sending data from Django's render() method to React.js

Currently, I'm working on a Django + React Application project where I am faced with the challenge of passing JSON data from Django's render() function to React.js. To achieve this, I initiate the rendering of an HTML page using Django, with the ...

What is the reason behind these sinon stubs returning undefined values?

I have created a unit test for this code snippet and used Sinon to stub the browser methods (specifically with sinon-chrome, an older but still functional library that suits my needs). /** * Returns an array of languages based on getAcceptLanguages and ge ...

I attempted to install react-compare-image using npm, but encountered an error stating that the dependency tree could not be resolved

PS D:\skinprojecct> npm install --save react-compare-image npm ERR! code ERESOLVE npm ERR! ERESOLVE unable to resolve dependency tree npm ERR! npm ERR! While resolving: [email protected] npm ERR! Found: [email protected] npm ERR! node_mod ...

Is there a way to trigger the activation of the datepicker during the `onLoad` event?

For my project, I am utilizing this datepicker. While I am familiar with using scripts to handle changes in the date value, I am unsure of how to implement it on page load. $('.date_set .date').datepicker({ startView : 0, ...

Why isn't useEffect recognizing the variable change?

Within my project, I am working with three key files: Date Component Preview Page (used to display the date component) useDateController (hook responsible for managing all things date related) In each of these files, I have included the following code sn ...

Error: Null value does not have a property 'tagName' to read

I am having trouble dynamically removing a CSS file from the head tag. I keep receiving this error message: Error: Unable to access property 'tagName' of null Here is my code: Link to CodeSandbox export default function IndexPage() { useEffe ...

Tips for postponing a function's execution in order to ensure it has completely loaded

I am facing an issue with a dynamic page that is populated by an ajax call. Here is the current code snippet: function loadPage() { var container = document.querySelector(".container"); var xhr = new XMLHttpRequest(); xhr.open('GET ...

Kohana ajax causing removal of JQuery Data attributes

Currently, I am developing an application where jquery data is used to pass variables to HTML elements. It has been successful in one part of the site when the data attributes are added to a tr tag. The following code works: <tr class="js-instructions ...

Prevent specific cells from being focused in ngGrid

Utilizing ngGrid to showcase data, I've encountered a dilemma with the cell templates. Some fields utilize a cell template to display an input field, while others do not. By using jQuery in my browser console, I attempted to remove the tabindex attri ...