AngularJS ngResource delete event
Asked Answered
R

2

5

I'm trying to keep a list of resources up to date as a user interacts with it. Using an AngularJS ngResource I initially grab the list using it's query method. Each resource then has a $remove (or $delete) method, right? But when fired, the resource isn't removed from the list returned from query.

This is asking a lot, I know, but I was almost hoping it would just do everything for me. Save that, how could I accomplish this. Does the resource itself emit some kind of event? Does it have a deleted property I can $watch? How would I go about know that a resource was $remove'd so I can splice it out of the list?

Thanks.

Reign answered 22/5, 2013 at 20:13 Comment(2)
Where is the code that you are referring to?Splenius
It's a real shame it doesn't handle this by itself. It would seem like a staringly obvious thing to do.Valenba
R
6

You have to use Array's splice method to remove it ($index is ng-repeat's implicit index).

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

And then in your HTML

<a ng-click="removeItem($index)">remove me</a>
Racecourse answered 22/5, 2013 at 20:16 Comment(2)
This will work most of the time, but what happens when there is some kind of error server-side. You UI will no longer reflect the correct state.Anywise
then you can pass it as a callback, I think :)Racecourse
A
2

Just use the success callback function:

instance.$action([parameters], [success], [error])

For you I am guessing that would be something like:

myResource.$delete([parameters], function () {
    //delete was successful
});
Anywise answered 22/5, 2013 at 20:24 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.