Use ngResource's $delete method to remove a record from a query object

Just starting out with angular and trying to work with the $resource library for API services. I'm having trouble figuring out how to delete a record obtained through the query() method. Specifically, we have an endpoint for user notifications. The goal is to fetch all user notifications on page load, iterate over them using ng-repeat, and display them in the navigation bar. When a user clicks on the remove icon, the corresponding notification should be deleted. Here's a simplified version of my current code:

Js:

angular.module('myapp', ['ngResource']).factory('Notifications',function($resource){
    return $resource('/apiv2/user/notifications/:id', {id:'@id'});
}).controller('NavigationController',['$scope','Notifications',function($scope, Notifications){
    $scope.notifications = Notifications.query();

    $scope.deleteNotification = function(notification){
        notification.$delete();
    };
}]);

HTML:

<ul>
    <li ng-repeat="notification in notifications">
        <i class="icon-remove" ng-click="deleteNotification(notification)"></i>
    </li>
</ul>

While this code works correctly in deleting the notification from the backend when the remove icon is clicked, the issue arises when examining the $scope.notifications object afterwards. The deleted notification still appears with broken data:

{$promise:undefined, $resolved:true}

The desired outcome is to completely remove the deleted record from the object returned by the .query() method without needing to run the query again.

Any assistance would be greatly appreciated! Please excuse any vague descriptions or errors in the code, as I wrote this from memory on my phone while out to dinner.

Answer №1

Improved method: (refer to AngularJS ngResource delete event)

$scope.removeNotification = function (index) {
  $scope.notifications[index].$delete();
  $scope.notifications.splice(index, 1);
}

To implement this in your HTML markup, simply use

ng-click="removeNotification($index)"

There might be a more efficient way to handle this as it currently results in a console error (though it still functions). Nevertheless, here is my approach:

$scope.notifications = Notifications.query();

$scope.removeNotification = function(notification){
    notification.$delete();
    $scope.notifications = $scope.notifications.filter( function(n)
        return (n != notification);
    }); // filter everything but
};

If you utilize underscore, there exists a more elegant solution for removing items.

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

How can I utilize the JQuery GetJSON function to retrieve HTML content from an external webpage?

Imagine you're attempting a jQuery ajax request like this: $.ajax({ ... url: http://other-website.com ... }) You probably know that due to the same-origin policy, this request will fail because the URL is for an external domain. But the ...

Develop a custom class for importing pipes in Angular 4

Currently, I am working on creating a pipe that will replace specific keywords with the correct strings. To keep this pipe well-structured, I have decided to store my keywords and strings in another file. Below is the code snippet for reference: import { ...

Tips for postponing the initialization of an AngularJS application

I have a set of data that is currently being processed in the background asynchronously. I want to delay the initialization of my AngularJS application until this process has been completed. The variable BackgroundData.initialized holds a Q promise, so I ...

CSS3 Perspective Issue: Solutions for Fixing

I'm currently working on creating a card flip animation that flips in the X axis direction. Right now, the div rotates using the rotateX() method. I attempted to add the perspective property to the upper div, but it ended up distorting my div structur ...

Storing input values in the state using Typescript by default

Upon launching, my activeField state is initially empty. However, when a user focuses on the field, it gets added to the state. I am encountering a warning in Typescript because when I attempt to update the selectionEnd of that field, it tells me: Property ...

Is Angular 1.5 the Best Choice for Structuring Component-Based Applications?

Lately, I've been constructing my application using the following arrangement. /src /components /shared /messagebox /alertbox /Home /About As you can observe, I have shared components that are utilized on ...

Modify the page's query parameters by incorporating an input field within NextJS's App Router

I'm trying to update query parameters based on user input dynamically using the onChange event. However, I'm facing an issue where the query parameters are updated before the input value is updated after a slight delay. My aim is to achieve insta ...

Methods for incorporating JSON Data into ChartJS

Below is my app.js file: app.js var app = angular.module('myApp', []); app.controller('MainCtrl', function($scope, $http) { $http.get('http://happyshappy.13llama.com/wp- json/llama/v1/stats').then(function(response) ...

Find the total number of records in fnClick: (datatables.net)

I am struggling with some code where I need to retrieve the total number of records. I posted about it on the datatables.net forum but unfortunately, no one was able to help me... tableTools: { "sSwfPath": window.STATIC_BASE + "scripts/datatable/s ...

React component experiencing double execution of SetTimeout function

Every time I render the App component, the code inside setTimeout seems to be running twice. I've noticed that setTimeout executes after the call stack is cleared. I wonder if this has any connection to the issue. Could it be related to how React ha ...

A guide to assigning multiple classes to an element in Vue.js depending on the props!

Take a look at my code to grasp the issue. <template> <div class="header" :class="flat ? 'flat' : null" :class="app ? 'app' : null"> </div> </template> <script> export default ...

Update the content within every <td> element using AJAX/JQUERY on a table created from JSP

I have a database filled with descriptions and corresponding ID numbers. The table displays them like this: index.jsp <table> <tr> <td>Name:</td> <td>Id:</td> </tr> <c:forEach items ...

What steps should I take to solve the issue of a black screen showing up once my React website has finished loading

Here's a photo showing error messages displayed on my website. Strangely, there are no errors appearing in my terminal and the website loads perfectly fine. However, I encountered some issues when trying to make styling changes using my dev tools. Aft ...

How can I convert the date format from ngbDatepicker to a string in the onSubmit() function of a form

I'm facing an issue with converting the date format from ngbDatepicker to a string before sending the data to my backend API. The API only accepts dates in string format, so I attempted to convert it using submittedData.MaturityDate.toString(); and su ...

"Step-by-step guide on implementing a click event within a CellRenderer in Angular's Ag-Grid

paste your code hereI'm currently working on implementing edit and delete buttons within the same column for each row using Angular ag-Grid. To visually represent these buttons, I am utilizing icons. While I have successfully displayed the edit and de ...

Subscriber client successfully activated and operational via the command line interface

I have incorporated a script into my PHP file that reads the Pusher channel and performs various actions when a new event occurs on the specified channel. If I access the following URL in my browser: http:/localhost/pusher.php and keep it open, the p ...

Using Jquery to show element when <select> is updated

I've been struggling to make this work due to my limited jquery/js skills. My goal is to have a different message displayed for each option selected from the dropdown menu for further information. <label class="checklabel">Is it possible to re ...

The array is remaining empty

When I need to loop through a JSON file, I typically use the following code snippet: var list = new Array(); $.getJSON("json.js", function (data) { $.each(data, function () { $.each(this, function (k, v) { var list = new Array(); ...

Ways to eliminate the Vuetify append-icon from the sequential keyboard navigation

In my Vue.js application using Vuetify, I have implemented a series of password fields using v-text-field with an append-icon to toggle text visibility. Here is the code snippet: <v-text-field v-model="password" :append-icon="show1 ? 'mdi-eye& ...

Shrink Table Column Size with Bootstrap and Stylus to Optimize Space Usage

Currently experimenting with Bootstrap to ensure my table is responsive on a search list I am developing. However, I am facing an issue where two of my columns are taking up more space than necessary. In the image below, you can see that Date and Link colu ...